EDIT
:
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
で長さフィルタリングを実行できます。
句読点を無視する場合は、を使用して不要な文字を削除するか、おそらくline.split()
の代わりにre.split(r'\W+', line)
を使用します。
このようにそれを試してみてください。
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回繰り返します。 –
1つの数字(20文字までの単語の数)または20の数字(潜在的な長さごとに、いくつの単語があるか)をお探しですか? – Mureinik
20個の数字を探します。最初の数字は1文字のファイル内の単語の数、2番目の数字は2文字などの単語の数です。 – Jonathan