我有以下代码,使用二进制搜索拼写单词。它将要拼写检查的文件与作为字典的文件进行比较,并返回所有拼写错误的单词。
拼写检查工作时,我将拼写错误的单词打印到终端,但现在我将它写入文件,它只能找到一小部分单词。
我还实施了一个计时器来计算搜索时间
import re
import time
start_time = time.time()
f1=open('writefile.txt', 'w+')
def binS(lo,hi,target):
if (lo>=hi):
return False
mid = (lo+hi) // 2
piv = words[mid]
if piv==target:
return True
if piv<target:
return binS(mid+1,hi,target)
return binS(lo,mid,target)
words = [s.strip("\n").lower() for s in open("words10k.txt")]
words.sort() # sort the list
text = open("shakespeare.txt" , encoding="utf8")
content = text.read().split(" ")
content = [item.lower() for item in content]
content = ' '.join(content)
content = re.findall("[a-z]+", content)
for w in content:
if not binS(0,len(words),w):
f1.write(w)
print("--- %s seconds ---" % (time.time() - start_time))
我有这段代码,之前通过打印到终端工作。 (我怎么能在写出文件中每行写1个字)
for w in content:
if not binS(0,len(words),w):
print(w)
通过打印到终端搜索时间:2000秒
通过写入文件来搜索时间:38秒
答案 0 :(得分:2)
打开文件后,我无法看到您关闭文件的位置。写入文件是缓冲的,因此这可能是一个原因。
更合适的方法是在您完成写作时使用with
语句正确关闭文件:
with open('writefile.txt', 'w+') as f1:
for w in content:
if not binS(0,len(words),w):
f1.write(w)
在其他新闻中:
set
存储words
,以便您进行有效的查找:if w not in words: ...
f1.writelines
和生成器表达式