
该语法
for line infin只能使用一次。完成此 *** 作后,您已经用尽了文件,除非您通过来“重置文件指针”,否则您将无法再次读取它
fin.seek(0)。相反,
fin.readlines()将为您提供一个列表,您可以反复遍历。
我认为使用
Counter(python2.7
+)进行简单的重构可以为您省去麻烦:
from collections import Counterwith open('file') as fin: result = Counter() for line in fin: result += Counter(set(line.strip().lower()))它将计算文件中包含特定字符的单词数(每行1个单词)(这是您认为原始代码的含义……如果我输入错了,请更正我)
您也可以使用
defaultdict(python2.5
+)轻松地做到这一点:
from collections import defaultdictwith 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) + 1fin.close()欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)