我会使用:
# mapping from soundex to correct word
soundex_to_ref = {jellyfish.soundex(w): w for w in ref_data}
for line in text1:
words = [soundex_to_ref.get(jellyfish.soundex(w), w) for w in line.split()]
这会为每一行生成一个单词列表,所有与拼写正确的单词匹配的单词都由soundex替换为正确的单词。
这个
[... for .. in ...]
语法是一种列表理解,它为
for
环所以,对于
line.split()
我们产生
soundex_to_ref.get(jellyfish.soundex(w), w)
表达式。
这个
soundex_to_ref
对象是一个字典,从
ref_data
列表对于列表中的每个单词,字典都有一个关键字(该单词的soundex值),该值是原始单词。这使我们可以轻松查找给定soundex的参考词。
dict.get()
让您在字典中查找关键字,如果是
不
如果存在,则返回默认值。
soundex.to_ref.get(水母.soundex(w),w)
为当前单词创建soundex
w
,查找参考单词,如果词典中不存在soundex,则替换原始单词。
您可以加入
words
使用以下方法将列表重新排列成一个句子:
line = ' '.join(words)
您可以重建
text1
在一个表达式中:
text1 = [' '.join([soundex_to_ref.get(jellyfish.soundex(w), w) for w in line.split()])
for line in text1]