2016-10-17 34 views
0

我正在嘗試在python中使用正則表達式語句來搜索文本文件並計算用戶定義的單詞出現的次數。當我運行我的代碼時,不是獲取文件中出現唯一字的次數的總和,而是獲取該文件中包含該字的數字行的計數。Python正則表達式搜索文本文件計數子串

例如:文本文件中存在56次單詞「apple」。出現在總共63行文字中的20行中。當我運行我的代碼時,控制檯打印'20'來代替'apple'而不是正確的'56'。

我想通過使用re.findall()方法它會解決這個問題,但它沒有。

import re 

#If user selects Regular Expressions as their search method 
elif user_search_method == "2": 
    print "\n>>> You selected the Regular Expressions search method" 
    f = open(filename, 'r') 
    words = sum(1 for w in f if re.findall(user_search_value, w, re.M|re.I)) 
    f.close() 
    print("Your search value of '%s' appears %s times in this file" % (user_search_value, words)) 
+0

這就是你問什麼因爲,雖然。 '1 for w in f' <這裏'w'是一行,你要根據'if re.findall(...)'進行過濾。如果你想計算找到的匹配數量,請總結'len(re.findall(...))'。 – jonrsharpe

回答

0

你只是加1,如果它匹配,我想你不希望搜索去了線,所以你可以這樣做:

words = sum(len(re.findall(user_search_value, w, re.M|re.I)) for w in f) 
+0

工作!謝謝。 – Ryan

相關問題