繁体   English   中英

用python中的正确单词替换字符串

[英]Replace the string with correct word in python

这是我的字符串,为此我将字符串拆分为单词

数据是正确单词的集合

句子是包含一些不正确单词的字符串,需要用更正的单词替换一次

data="blue whale","red rose","city of joy","dream pride","rain drops","ten house","think twice"
data=[words for segments in data for words in segments.split()]

sentence = ["I'll have to thnik twycee before going to ceety of joiy along with red rossy"]
sentence = sentence.split()

现在我正在尝试拼写检查

 def words(text): return re.findall(r'\w+', text.lower())
    WORDS = Counter(data)

    def P(word, N=sum(WORDS.values())): 
        "Probability of `word`."
        return WORDS[word] / N

    def correction(word): 
        "Most probable spelling correction for word."
        return max(candidates(word), key=P)

    def candidates(word): 
        "Generate possible spelling corrections for word."
        return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

    def known(words): 
        "The subset of `words` that appear in the dictionary of WORDS."
        return set(w for w in words if w in WORDS)

    def edits1(word):
        "All edits that are one edit away from `word`."
        letters    = 'abcdefghijklmnopqrstuvwxyz'
        splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
        deletes    = [L + R[1:]               for L, R in splits if R]
        transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
        replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
        inserts    = [L + c + R               for L, R in splits for c in letters]
        return set(deletes + transposes + replaces + inserts)

    def edits2(word): 
        "All edits that are two edits away from `word`."
        return (e2 for e1 in edits1(word) for e2 in edits1(e1))

现在我要做的是我要用更正的单词替换所有不正确的单词并更新对象句子

更正('thnik')

O / P

认为

用于更新对象“句子”的代码

for i  in sentence:
        sentence = correction(i)
        sentence = [sentence.append(i)]
        print(sentence)

因为程序将检查所有给定的单词并输出结果,所以我将使用sentence = ' '.join(sentence) join sentence = ' '.join(sentence)将它们全部加入,但是for循环代码给出了我的错误"AttributeError: 'str' object has no attribute 'append'" ,任何帮助将不胜感激。 谢谢

sentence = "Thsi is my cdoe"   #Lets assume this is your sentence.    
formatted_sentence = ''
for i  in sentence:
    corrected_word = correction(i) # if "Thsi" is passed to correction it should return "This" 
    formatted_sentence += ' '.join(corrected_word)
print(formatted_sentence)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM