-3

私が欲しいのは、長い段落のような複数行のテキストファイルをフィードして、次のようなもので返すことができるようにすることです:

{'Total words': 'NUMBER', 'Words ending with LY': 'NUMBER'}

以前にカウンターを使用したことはありませんが、それが私が行う方法だと思います。したがって、すべての単語をカウントし、単語が LY で終わる場合は、それを 2 番目のカウントに追加します。カウンターを使ったことがないので、どこに行けばいいのかわかりません...

with open('SOMETHING.txt') as f:
  # something to do with counter here?

編集:カウンターを使わずにやらなければなりません!どうすれば同じ結果を得ることができますが、カウンター ライブラリはありませんか?

4

3 に答える 3

1

これはあなたのために働くはずです...

def parse_file():
  with open('SOMETHING.txt', 'r') as f:
    c1 = 0
    c2 = 0
    for i in f:
      w = i.split()
      c1 += len(w)
      for j in w:
        if j.endswith('LY'):
          c2 += 1
    return {'Total words': c1, 'Words ending with LY': c2}

ただし、いくつかの python basicsをご覧になることをお勧めします。

于 2013-08-29T08:21:35.977 に答える
0

これを試すのは難しいですか?

from collections import defaultdict
result = defaultdict(int)
result_second = defaultdict(int)
for word in open('text.txt').read().split():
    result[word] += 1
    if word.endswith('LY'): 
        result_second[word] +=1
print result,result_second

出力:

defaultdict(<type 'int'>, {'and': 1, 'Considering': 1, 'have': 2, "don't": 1, 'is': 1, 'it': 2, 'second': 1, 'want': 1, 'in': 1, 'before': 1, 'would': 1, 'to': 3, 'count.': 1, 'go...': 1, 'how': 1, 'add': 1, 'if': 1, 'LY': 1, 'it.': 1, 'do': 1, 'ends': 1, 'used': 2, 'that': 1, 'I': 1, 'Counter': 2, 'but': 1, 'So': 1, 'know': 1, 'never': 2, 'believe': 1, 'count': 1, 'word': 2, 'i': 5, 'every': 1, 'the': 2, 'where': 1})
于 2013-08-29T08:21:49.550 に答える