您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中遍历文件对象不起作用,但是readlines()可以,但是效率低下

在Python中遍历文件对象不起作用,但是readlines()可以,但是效率低下

该语法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()
python 2022/1/1 18:40:56 有307人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶