使用二进制搜索拼写Ch

2024-09-28 22:31:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用二进制搜索来检查文件中单词的拼写,并打印出字典中没有的单词。但到目前为止,大多数拼写正确的单词都被打印成拼写错误(字典中找不到的单词)。 字典文件也是一个文本文件,它看起来像:

abactinally
abaction
abactor
abaculi
abaculus
abacus
abacuses
Abad
abada
Abadan
Abaddon
abaddon
abadejo
abadengo
abadia

代码:

^{pr2}$

Tags: 文件字典二进制单词文本文件abacus拼写错误abacuses
1条回答
网友
1楼 · 发布于 2024-09-28 22:31:34

你的二进制搜索工作完美!不过,你似乎没有删除所有的特殊字符。在

测试你的代码(用我自己的一句话):

def main():

   print("This program performs a spell-check in a file")
   print("and prints a report of the possibly misspelled words.\n")

   text = 'An old mann gathreed his abacus, and ran a mile.  His abacus\n ran two miles!'
   for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
       text = text.replace(ch, ' ')
   words = text.lower().split(' ')

   dic = ['a','abacus','an','and','arranged', 'gathered', 'his', 'man','mile','miles','old','ran','two']

   #perform binary search for misspelled words
   misw = []
   for w in words:
       m = binSearch(w,dic)
       if m == -1:
           misw.append(w)
   print misw

打印为输出['mann', 'gathreed', '', '', 'abacus\n', '']

这些额外的空字符串''是标点符号的额外空格,您可以用空格代替它们。\n(换行符)有点问题,因为您可以在外部文本文件中看到它,但不能直观地解释它。您应该做的不是for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_``{|}~':只需检查每个字符.isalpha()请尝试以下操作:

^{pr2}$

输出:

This program performs a spell-check in a file
and prints a report of the possibly misspelled words.

['mann', 'gathreed']

希望这对你有帮助!如果你需要澄清或者有什么不起作用的话,请随时发表意见。在

相关问题 更多 >