该语法for line in fin
只能使用一次。完成此操作后,您已经用尽了文件,除非您通过来“重置文件指针”,否则您将无法再次读取它fin.seek(0)
。相反,fin.readlines()
将为您提供一个列表,您可以反复遍历。
我认为使用Counter
(python2.7 +)进行简单的重构可以为您省去麻烦:
from collections import Counter
with open('file') as fin:
result = Counter()
for line in fin:
result += Counter(set(line.strip().lower()))
它将计算文件中包含特定字符的单词数(每行1个单词)(这是您认为原始代码的含义……如果我输入错了,请更正我)
您也可以使用defaultdict
(python2.5 +)轻松地做到这一点:
from collections import defaultdict
with open('file') as fin:
result = defaultdict(int)
for line in fin:
chars = set(line.strip().lower())
for c in chars:
result[c] += 1
最后,把它踢得很老套-我什至不知道什么时候setdefault
被介绍…:
fin = open('file')
result = dict()
for line in fin:
chars = set(line.strip().lower())
for c in chars:
result[c] = result.setdefault(c,0) + 1
fin.close()