2013-08-29 49 views
-3

我要的是能够在多行文本文件,该文件是像长一段喂,然后用类似退货:计数在一个文本文件蟒蛇的每一个字

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

我从来没有使用Counter之前,但我相信这是我会做到这一点。所以我希望它能够统计每个单词,如果单词以LY结尾,则将其添加到第二个计数中。考虑到我从来没有使用过柜台,我不知道哪里去了......

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

编辑:我必须这样做,而不使用计数器!我如何达到相同的结果,但没有柜台库?

回答

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

+0

谢谢!就是我想要的!我认为我可以让它更清洁一点,但.. – NoviceProgrammer

+0

有它。感觉自由:) –

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}) 
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} 
+0

我已经添加了一个没有柜台的解决方案。 – Blubber

+0

小心,read()会将整个文件加载到内存中。如果文件很大,则可能会耗尽系统的RAM内存。 –