这是我的字符串,我已将字符串拆分为单词
数据是正确单词的集合
句子是包含一些不正确单词的字符串,需要用更正后的单词替换
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&#39)
O / P
认为
用于更新对象的代码"句子"
for i in sentence:
sentence = correction(i)
sentence = [sentence.append(i)]
print(sentence)
由于程序将检查所有给定的单词并输出结果,我会使用sentence = ' '.join(sentence)
加入它们
但for循环代码给出了我的错误"AttributeError: 'str' object has no attribute 'append'"
,任何帮助都会非常感激。感谢
答案 0 :(得分:1)
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)