编辑
为了生产单独计数每个单词的长度,你可以使用一个collections.Counter
:
from collections import Counter
def word_lengths(f):
for line in f:
for word in line.split(): # does not ignore punctuation
yield len(word)
with open('words.txt') as fin:
counts = Counter(length for length in word_lengths(fin) if length <= 20)
它使用发电机来读取文件并产生字长的序列。过滤的字长被输入Counter
。您可以改为在Counter
上执行长度过滤。
如果您想忽略标点符号,可以使用str.translate()
删除不需要的字符,或者可能使用re.split(r'\W+', line)
而不是line.split()
。
试试这样说:
with open('words.txt') as fin:
counter = 0
for line in fin:
for word in line.split():
if len(word) <= 20:
counter = counter + 1
print counter,
这可以简化为:
with open('words.txt') as fin:
counter = sum([1 for line in fin
for word in line.split() if len(word) <= 20])
但是这打码高尔夫球。
你也可以使用一个collections.Counter
,如果它是可行的整个文件读入内存:
from collections import Counter
with open('words.txt') as fin:
c = Counter(fin.read().split())
counter = sum(c[k] for k in c if len(k) <= 20)
毫无疑问,还有很多其他的方法来做到这一点。以上都不期望或处理标点符号。
程序逻辑是完全向后。而不是迭代文件并查找20个字符的单词,而是遍历该文件20次。 –
你正在寻找一个数字(字数不超过20个字符)或20个数字(每个潜在的长度,有多少字)? – Mureinik
寻找20个数字,这意味着第一个数字是文件中包含1个字母的字数,第二个数字是包含2个字母等字的数量... – Jonathan