2013-08-29 48 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內存。 –