我想知道,如何读取像 fscanf 这样的字符串。我需要在 all .txt 中逐字阅读。 我需要对每个单词进行计数。
collectwords = collections.defaultdict(int)
with open('DatoSO.txt', 'r') as filetxt:
for line in filetxt:
v=""
for char in line:
if str(char) != " ":
v=v+str(char)
elif str(char) == " ":
collectwords[v] += 1
v=""
这样一来,我就看不到最后一个字了。
请您参考如下方法:
如果您使用的是 Python >=2.7
,您还可以考虑使用collections.counter
http://docs.python.org/library/collections.html#collections.Counter
它添加了一些方法,例如“most_common”,这在此类应用程序中可能很有用。
来自 Doug Hellmann 的 PyMOTW:
import collections
c = collections.Counter()
with open('/usr/share/dict/words', 'rt') as f:
for line in f:
c.update(line.rstrip().lower())
print 'Most common:'
for letter, count in c.most_common(3):
print '%s: %7d' % (letter, count)
http://www.doughellmann.com/PyMOTW/collections/counter.html -- 虽然这是字母计数而不是单词计数。在 c.update 行中,您可能希望将 line.rstrip().lower 替换为 line.split() 和一些代码去掉标点符号。
编辑:删除标点符号可能是最快的解决方案:
import collections
import string
c = collections.Counter()
with open('DataSO.txt', 'rt') as f:
for line in f:
c.update(line.translate(string.maketrans("",""), string.punctuation).split())
(借自以下问题 Best way to strip punctuation from a string in Python )
