2013-04-24 141 views
0

我有以下程序,我想在我的文本文件中找到例如字符串「淺粉紅色」!我使用,它不起作用。計算文本文件中字符串的出現次數

from operator import itemgetter 

def mmetric1(file): 
    words_gen = (word.lower() for line in open("test.txt") 
              for word in line.split()) 
    words = {} 

    for word in words_gen: 
     if (word=='aqua')or(word=='azure')or(word=='black')or(word=='light pink'): 
      words[word] = words.get(word, 0) + 1 

    top_words = sorted(words.items(), key=itemgetter(1)) 

    for word, frequency in top_words: 
     print ("%s : %d" % (word, frequency)) 
+0

你應該考慮使用正則表達式。 – DhruvPathak 2013-04-24 09:16:29

+1

看看[Aho-Corasick算法](https://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/) – 2013-04-24 10:50:24

+0

保護這個問題,很多年前被一個不活躍的用戶問過,不太可能得到接受的答案 - 只是吸引糟糕的編輯。 – 2016-01-10 12:25:13

回答

1

您已經分裂了整個行成單獨的詞:

for word in line.split() 

所以在words_gen其中包含文本light pink沒有一個字。它包含lightpink作爲兩個單獨的單詞,以及該行上的所有其他單詞。

您需要一種不同的方法;看看正則表達式。

+0

謝謝你的回答 – user2314768 2013-04-24 09:55:02

0

拆分一個字符串,它的分裂基礎上的空白,其中包括空格字符

所以後來,就沒有可能讓你在你提出細讀除非

的方式匹配連續字
  • 您wan't修改循環

示例代碼

try: 
    while True: 
     word = next(words_gen) 
     if any(word == token for token in ['aqua', 'azure', 'black']) \ 
      or (word == 'light' and next(word) == 'pink'): 
      words[word] = words.get(word, 0) + 1 
except StopIteration: 
    pass 
  • 使用正則表達式

不是一個好的選擇,如果你正在尋找一個巨大的文件

  • 使用一些其他的數據結構是怎樣的前綴樹
+0

你是說我會在我的程序中添加一個異常? – user2314768 2013-04-24 09:55:34

+0

@ user2314768:在Python世界中使用異常控制流是可以接受的 – Abhijit 2013-04-24 11:43:23

1

你的整個做法是錯誤。

在我看來,你想檢查你的文件中是否存在一組字符串。你應該使用正則表達式。

這裏:

from collections import Counter 
import re 

def mmetric1(file_path, desired): 
    finder = re.compile(re.escape('(%s)' % '|'.join(desired)), re.MULTILINE) 
    with open(file_path) as f: 
     return Counter(finder.findall(f)) 

# have a list of the strings you want to find 
desired = ['aqua', 'azure', 'black', 'light pink'] 
# run the method 
mmetric1(file_path, desired) 

如果你擔心大文件和性能,您可以通過行遍歷文件中:

def mmetric1(file_path, desired): 
    results = Counter() 
    finder = re.compile(re.escape('(%s)' % '|'.join(desired))) 
    with open(file_path) as f: 
     for line in f: 
      Counter.update(finder.findall(line)) 
    return results 

打印這些結果因爲你有你自己的:

for word, frequency in mmetric1(file_path, desired).items(): 
    print ("%s : %d" % (word, frequency)) 
+0

謝謝,我會試試這個 – user2314768 2013-04-24 09:54:38

+0

因爲我是一個在參數file_path中編寫Python的初學者,我可以寫什麼?我想加載「test.txt」文件 – user2314768 2013-04-24 10:02:36

+0

是的,你需要簡單地把文件的路徑作爲'file_path',你使用'file'作爲變量名,'file'是一個Python類型,你正在遮蔽它。 – 2013-04-24 11:15:09

相關問題