我有一个句子列表,基本上我的目标是用正确的拼写“opposite,near,above,behind”替换所有不同的介词“opp,nr,off,abv,behnd”等等在。单词的 soundex 代码相同,所以我需要构建一个表达式来逐字遍历此列表,如果 soundex 相同,则将其替换为正确的拼写。
一个例子——
[' jack 站在树旁',
“他们是他计划的一切”,
'站在柜台对面',
'去加油站']
所以我需要用正确的完整形式替换单词 nr、abv、opp 和 twrds。 towards和twrds的soundex代码是一样的,应该换掉。
我需要遍历这个列表..
这是 soundex 算法:
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())
我是新手,所以如果您可以建议另一种方法,我们将不胜感激..谢谢。
最佳答案
我将使用附魔模块:
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])
关于python - 使用 Soundex, python 替换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21628391/