我正在尝试使用二进制搜索来检查文件中单词的拼写,并打印出不在字典中的单词。但截至目前,大多数正确拼写的单词都被拼写为拼写错误(在字典中找不到的单词)。 字典文件也是一个文本文件,如下所示:
abactinally
abaction
abactor
abaculi
abaculus
abacus
abacuses
Abad
abada
Abadan
Abaddon
abaddon
abadejo
abadengo
abadia
代码:
def binSearch(x, nums):
low = 0
high = len(nums)-1
while low <= high:
mid = (low + high)//2
item = nums[mid]
if x == item :
print(nums[mid])
return mid
elif x < item:
high = mid - 1
else:
low = mid + 1
return -1
def main():
print("This program performs a spell-check in a file")
print("and prints a report of the possibly misspelled words.\n")
# get the sequence of words from the file
fname = input("File to analyze: ")
text = open(fname,'r').read()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
text = text.replace(ch, ' ')
words = text.split()
#import dictionary from file
fname2 =input("File of dictionary: ")
dic = open(fname2,'r').read()
dic = dic.split()
#perform binary search for misspelled words
misw = []
for w in words:
m = binSearch(w,dic)
if m == -1:
misw.append(w)
答案 0 :(得分:0)
您的二分查找效果非常好!但是,您似乎并没有删除所有特殊字符。
测试你的代码(用我自己的句子):
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()
是否尝试这个:
def main():
...
text = 'An old mann gathreed his abacus, and ran a mile. His abacus\n ran two miles!'
for ch in text:
if not ch.isalpha() and not ch == ' ':
#we want to keep spaces or else we'd only have one word in our entire text
text = text.replace(ch, '') #replace with empty string (basically, remove)
words = text.lower().split(' ')
#import dictionary
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
输出:
This program performs a spell-check in a file
and prints a report of the possibly misspelled words.
['mann', 'gathreed']
希望这有用!如果您需要澄清或有些不起作用,请随时发表评论。