This is what I have so far:

def stats(filename):
    ' prints the number of lines, words, and characters in file filename'
    infile = open(filename)
    lines = infile.readlines()
    words = infile.read()
    chars = infile.read()
    infile.close()
    print("line count:", len(lines))
    print("word count:", len(words.split()))
    print("character counter:", len(chars))

执行时,正确返回行数,但单词和字符计数返回0。。。。

最佳答案

您需要在读取结束位置后用infile.seek(0)返回到文件开头,seek(0)将其重置为开始位置,以便您可以再次读取。

infile = open('data')
lines = infile.readlines()
infile.seek(0)
print(lines)
words = infile.read()
infile.seek(0)

chars = infile.read()
infile.close()
print("line count:", len(lines))
print("word count:", len(words.split()))
print("character counter:", len(chars))

输出:
line count: 2
word count: 19
character counter: 113

其他方式
from collections import Counter
from itertools import chain
infile = open('data')

lines = infile.readlines()
cnt_lines = len(lines)

words = list(chain.from_iterable([x.split() for x in lines]))
cnt_words = len(words)

cnt_chars = len([ c for word in words  for c in word])

# show words frequency
print(Counter(words))

关于python - 使用Python打印出字符,单词和行数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32927896/

10-10 02:30