-3

我想要的是能够输入一个多行文本文件,该文件就像一个段落一样长,然后返回如下内容:

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

我以前从未使用过 Counter,但我相信我会这样做。所以我希望它计算每个单词,如果单词以 LY 结尾,则将其添加到第二个计数中。考虑到我从未使用过 Counter 我不知道该去哪里...

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 基础知识

于 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 回答
0

使用 collections.Counter()

import collections

with open('your_file.txt') as fp:
    text = fp.read()
    counter = collections.Counter(['ends_in_ly' if token.endswith('LY') else 'doesnt_end_in_ly' for token in text.split()])

无柜台

with open('file.txt') as fp:
    tokens = fp.read().split()
    c = sum([1 if token.endswith('LY') else 0 for token in tokens])
    return {'ending_in_ly': c, 'not_ending_in_ly': len(tokens) - c}
于 2013-08-29T08:42:03.167 回答