[英]Counting words in list using a dictionary
我有一個詞典列表,其中包含一個單詞和該單詞的一些拼寫錯誤。 我試圖遍歷字符串列表,首先計算單詞的出現次數,然后計算每個拼寫錯誤的發生次數。 我嘗試使用if word in string
但這最終給了我錯誤的計數,因為許多拼寫錯誤包含其中的實際單詞本身。 是否可以在此處使用pythons counter
,還是使用正則表達式更有意義?
例如我有
words = [{'word':'achieve','misspellings': ['acheive','acheiv','achiev']},
{'word':'apparently','misspellings':['apparantly','apparintly']}]
我正在尋找一個字符串列表,最后包含每個單詞及其拼寫錯誤的總數。 我在使用achiev這樣的拼寫錯誤時遇到問題,當使用if word in string
計數時if word in string
會混淆計數,因為在實現中會達到achiev,因此計數將關閉。
您應該將拼寫錯誤的單詞映射到原始單詞:
words = {'acheive':'achieve', 'achiev':'achieve','achieve':'achieve'}
s = "achiev acheive achieve"
from collections import Counter
from string import punctuation
cn = Counter()
for word in s.split():
word = word.strip(punctuation)
if word in words:
wrd = words[word]
cn[wrd] += 1
print(cn)
Counter({'achieve': 3})
您可以將其與正則表達式結合使用,以查找字符串中的所有單詞,而不必按照Tim Pietzcker的答案進行拆分。
要計算拼寫錯誤的單詞和原始單詞,只需檢查單詞字典查找返回的值是否等於單詞,如果是,則更新單詞的原始計數,否則更新未命中計數:
words = {'acheive':'achieve', 'achiev':'achieve','achieve':'achieve',
'apparently':'apparently','apparantly':'apparently','apparintly':'apparently'}
s = "achiev acheive achieve! 'apparently' apparintly 'apparantly?""
from collections import defaultdict
from string import punctuation
cn = defaultdict(lambda:{"orig": 0 ,"miss":0})
for word in s.split():
word = word.strip(punctuation)
if word in words:
wrd = words[word]
if wrd == word:
cn[wrd]["orig"] += 1
else:
cn[wrd]["miss"] += 1
print(cn)
defaultdict(<function <lambda> at 0x7f001fb2a8c0>,
{'apparently': {'miss': 2, 'orig': 1}, 'achieve': {'miss': 2, 'orig': 1}})
正則表達式可能是一個很好的工具- 單詞邊界錨可以幫助您避免單詞內的子匹配。
對於每個單詞,使用wordre = re.compile(r"\\b" + word + r"\\b", re.I|re.U)
構建一個正則表達式,然后計算re.findall(wordre, string)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.