代码之家  ›  专栏  ›  技术社区  ›  Hypothetical Ninja

用相同的soundex替换单词

  •  0
  • Hypothetical Ninja  · 技术社区  · 11 年前

    我有一个介词拼写错误的句子列表。我有一份拼写正确的准备列表:

    ref_data = ['near','opposite','off','towards','behind','ahead','below','above','under','over','in','inside','outside']
    

    我需要从我的数据中计算单词的soundex,如果soundex匹配,则用我的参考单词替换。。这是我的代码:

    for line in text1:
    for word in line.split():
        if jellyfish.soundex(word)==jellyfish.soundex([words,int in enumerate(ref_data)])
           word = #replace code here
    

    我真的很困惑。。文本1包含[“他在喷泉里”,……更多]等句子。请帮忙。。我的语法错误。。

    1 回复  |  直到 11 年前
        1
  •  1
  •   Martijn Pieters    11 年前

    我会使用:

    # 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]