[英]How do I count the number of occurrences of a list of items in another .txt file?
我有一個單詞列表,我想找到它們在.txt文件中出現了多少次。 單詞列表如下所示:
wordlist = ['cup', 'bike', 'run']
我不僅希望能夠撿起這些單詞,而且還能撿起CUP,騎自行車的人,跑步,杯賽之類的東西。所以我認為我需要一個正則表達式。 這是我在想的,但是不起作用:
len(re.findall(wordlist, filename, re.I))
提前致謝!
你近了 但是re.findall
采用模式和字符串,而不是單詞列表和文件名。
但是,如果您將文件讀取為字符串並將單詞表轉換為模式,那么您會得到它。
您需要的模式將如下所示: r"cup|bike|run"
。 您可以執行"|".join(wordlist)
來實現。
這是計算所有這些實例的非常寬松的方法。 請注意,如果文件中包含“我的警棍已被re.findall
” re.findall
,則re.findall
會在較大的單詞中找到“ run”和“ cup”。 因此,您可能需要調整模式以捕捉單詞的開頭和結尾。
要僅獲取整個單詞,請使用以下模式: r"\\b(cup|bike|run)\\b"
。 當然,您需要填寫要查找的所有單詞變體。
正則表達式需要工作,但這應該可以幫助您入門:
from __future__ import with_statement # only if < 2.6
from collections import defaultdict
import re
matches = defaultdict(int)
with open(filename) as f:
for mtch in re.findall(r'\b(cup|bike|run)', f.read(), re.I):
matches[mtch.lower()] += 1
您將首先要猜測所有形式的單詞,這似乎是PITA 。 但是這是我在閱讀http://www.theenglishspace.com/spelling/之后寫的一個簡化的fn:
def getWordForms(word):
''' Given an English word, return list of possible forms
'''
l = [word]
if len(word)>1:
l.extend([word + 's', word + 'ing', word + 'ed'])
wor, d = word[:-1], word[-1:]
if d == 'e':
l.append(word + 'd')
l.append(wor + 'ing')
if wor[-1:] == 'f':
l.append(wor[:-1] + 'ves')
elif d == 'y':
l.append(wor + 'ied')
l.append(wor + 'ies')
elif d == 'z':
l.append(word + 'zes') # double Z
elif d == 'f':
l.append(wor + 'ves')
elif d in 'shox':
l.append(word + 'es')
if re.match('[^aeiou][aeiou][^aeiou]', word):
l.append(word + d + 'ing') # double consonant
l.append(word + d + 'ed')
return l
它猜測的單詞變體過於寬大-但這沒關系,因為它不是拼寫檢查器,並且您將在兩側使用\\ b來表示單詞邊界。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.