首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Soundex、python替换单词

使用Soundex、python替换单词
EN

Stack Overflow用户
提问于 2014-02-07 20:56:45
回答 1查看 2.6K关注 0票数 4

我有一个句子列表,基本上我的目标是将所有不同的介词形式"opp,nr,off,abv,behnd“替换为正确的拼写”对立面,近处,上方,后面“等等。单词的soundex代码是相同的,所以我需要构建一个表达式来逐个单词地迭代这个列表,如果soundex是相同的,就用正确的拼写替换它。

一个例子-[‘杰克站在树上’,

代码语言:javascript
复制
     'they were abv everything he planned' ,
代码语言:javascript
复制
 'Just stand opp the counter' ,
代码语言:javascript
复制
 'Go twrds the gas station']

所以我需要用正确的完整形式替换单词nr,abv,opp和twrds。方向和twrds的soundex代码是相同的,所以应该替换它。

我需要遍历这个列表。

以下是soundex算法:

代码语言:javascript
复制
import string

allChar = string.uppercase + string.lowercase
charToSoundex = string.maketrans(allChar, "91239129922455912623919292" * 2)

def soundex(source):
    "convert string to Soundex equivalent"

    # Soundex requirements:
    # source string must be at least 1 character
    # and must consist entirely of letters
    if (not source) or (not source.isalpha()):
    return "0000"

    # Soundex algorithm:
    # 1. make first character uppercase
    # 2. translate all other characters to Soundex digits
    digits = source[0].upper() + source[1:].translate(charToSoundex)

    # 3. remove consecutive duplicates
    digits2 = digits[0]
    for d in digits[1:]:
        if digits2[-1] != d:
           digits2 += d

    # 4. remove all "9"s
    # 5. pad end with "0"s to 4 characters
    return (digits2.replace('9', '') + '000')[:4]

if __name__ == '__main__':
   import sys
   if sys.argv[1:]:
      print soundex(sys.argv[1])
   else:
    from timeit import Timer
    names = ('Woo', 'Pilgrim', 'Flingjingwaller')
    for name in names:
        statement = "soundex('%s')" % name
        t = Timer(statement, "from __main__ import soundex")
        print name.ljust(15), soundex(name), min(t.repeat())

我是一个新手,所以如果你有其他的建议,我将不胜感激。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2014-10-03 17:16:43

我将使用enchant模块:

代码语言:javascript
复制
import enchant
d = enchant.Dict("en_US")

phrase = ['Jack was standing nr the tree' ,
'they were abv everything he planned' ,
'Just stand opp the counter' ,
'Go twrds the gas station']

output = []
for section in phrase:
    sect = ''
    for word in section.split():
        if d.check(word):
            sect += word + ' '
        else:
            for correct_word in d.suggest(word):
                if soundex(correct_word) == soundex(word):
                    sect +=  correct_word + ' '
    output.append(sect[:-1])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21628391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档