在下面的代码中,如果我使用:
for line in fin:
它只对 'a' 执行
但如果我使用:
wordlist = fin.readlines()
for line in wordlist:
然后它执行 a thru z。
But readlines()
立即读取整个文件,这是我不想要的。
如何避免这种情况?
def avoids():
alphabet = 'abcdefghijklmnopqrstuvwxyz'
num_words = {}
fin = open('words.txt')
for char in alphabet:
num_words[char] = 0
for line in fin:
not_found = True
word = line.strip()
if word.lower().find(char.lower()) != -1:
num_words[char] += 1
fin.close()
return num_words
语法for line in fin
只能使用一次。执行此操作后,您将耗尽该文件,并且无法再次读取它,除非您通过以下方式“重置文件指针”fin.seek(0)
。反过来,fin.readlines()
会给你一个可以一遍又一遍迭代的列表。
我认为一个简单的重构Counter http://docs.python.org/2/library/collections.html#collections.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 http://docs.python.org/2/library/collections.html#collections.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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)