2016-11-17 37 views
0

所以我的問題是我已經創建了一個名爲「GA」另一個腳本的陣列來存儲單詞作爲最終它可以容納100 +單詞。我試圖然後調用這個數組並搜索另一個txt文檔中的單詞並輸出每個單詞被找到的次數。在我的代碼'def ReadFile'的第一部分,我打開文件清理它,並顯示這些單詞所在的行。的Python 3字多少次從數組出現在文件

問題本身是我似乎無法找到一種方法來顯示輸入單詞以及輸出每個單詞的次數,這裏是我的代碼。

import re 
from collections import Counter 
from Categories.GoingAce import GA 

path = "ChatLogs/Chat1.txt" 
file = path 

Lex = Counter(GA) 

count = {} 

def ReadFile(): 

    with open(file) as file_read: 
     content = file_read.readlines() 
     for line in content: 
      if any(word in line for word in Lex): 
       Cleanse = re.sub('<.*?>', '', line) 
       print(Cleanse) 

    file_read.close() 

def WordCount(): 

    with open(file) as f: 
     Lex = Counter(f.read().split()) 
    for item in Lex.items(): print ("{}\t{}".format(*item)) 
    f.close() 


#ReadFile() 
WordCount() 

原始輸入看起來像這樣

<200> <ilovethaocean> <08/22/06 12:15:36 AM> hi asl? 
<210> <a_latino_man559> <08/22/06 12:15:53 AM> 32 m fresno 
<210> <a_latino_man559> <08/22/06 12:15:53 AM> u? 
<200> <ilovethaocean> <08/22/06 12:16:12 AM> "13/f/ca, how r u?" 
<200> <a_latino_man559> <08/22/06 12:16:18 AM> 13? 

然後我用這個隱藏在括號中的一切:

Cleanse = re.sub('<.*?>', '', line) 
        print(Cleanse) 

,其輸出是這樣的:

喜翔升?

32米弗雷斯諾

U&

「13/F/CA,如何[R u?舉報」

13?

隨着作爲比方說我的GA數組包含一個例子(喜,U 13)我的完美的目標會是這樣的輸出:

喜出現1次 line_num喜翔升?

ü出現2次 line_numú?

line_num 13/F/CA,如何[R u?舉報

+0

你能修復縮進pl嗎?緩解? – Bahrom

+0

我不明白它的外觀有什麼問題,看起來不錯? – Lewis20

+0

看看你的功能,兩個功能的主體都沒有縮進。 – Bahrom

回答

0

下面是一個簡單的例子的方法:

from collections import defaultdict 

occurrences = defaultdict(list) 
words = ['cat', 'dog', 'bird', 'person'] 

with open(path_to_your_file) as f: 
    for i, line in enumerate(f.readlines(), start=1): 
     for word in words: 
      if word in line: 
       occurrences[word] += [(i, line)] 

for (word, matches) in occurrences.items(): 
    total_count = sum(line.count(word) for _, line in matches) 
    print '%s appeared %d time(s). Line(s):' % (word, total_count) 
    print '\n'.join(['\t %d) %s' % (line_num, line.strip()) for line_num, line in matches]) 

鑑於包含以下內容的文本文件:

cat, rat, dog, cat 
bird, person 
animal 
insect 
whatever 
another bird 
etc. 

腳本打印

bird appeared 2 time(s). Line(s): 
    2) bird, person 
    6) another bird 
person appeared 1 time(s). Line(s): 
    2) bird, person 
dog appeared 1 time(s). Line(s): 
    1) cat, rat, dog, cat 
cat appeared 2 time(s). Line(s): 
    1) cat, rat, dog, cat 
+0

感謝您的解決方案是什麼部分我要找的,但不幸的是我需要它來顯示這句話,然後只給每個字多少次出現在年底的總數或有兩個分裂成不同的功能因爲我已經嘗試過 – Lewis20

+0

@Lewis20,你可以發佈一個樣例清單的輸入文件內容(所以不需要我亂七八糟的正則表達式)和樣本列表的單詞和期望的輸出?然後,我將編輯我的問題以供您使用。 – Bahrom

+0

我已經添加了一個樣本,盡我所能解釋我在 – Lewis20

相關問題