计算文本文件python中的每个单词

时间:2013-08-29 08:09:31

标签: python python-3.x counter

我想要的是能够提供一个多行的文本文件,这个文件就像段落一样长,然后用以下内容返回:

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

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

with open('SOMETHING.txt') as f:
  # something to do with counter here?
编辑:我必须不使用计数器!如何获得相同的结果,但没有计数器库?

3 个答案:

答案 0 :(得分: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}

我建议你看一下a few python basics

答案 1 :(得分: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})

答案 2 :(得分: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}