我一直在从事python项目。而且我想知道如何执行二进制搜索来搜索和匹配文本文件中的单词(txt文件中包含近13000个单词。)就像用户键入单词时,我必须搜索该单词是是否在文件中。单词被排序。
这是我尝试在文件中搜索的方式,但是没有用。
def find_word('words.txt', target_word):
target_word = ""
start = 0
end = len('words.txt') - 1
while start <= end:
middle = (start + end) // 2
midpoint = 'words.txt'(middle)
if midpoint > target_word:
end = midpoint - 1
elif midpoint < target_word:
start = midpoint + 1
else:
return midpoint
这是一个测试文件。
import re
a_word =“测试”
a_file =“ mytextfile.txt”
a_pattern = a_word
a_text =“您好,这是一个测试。”
m = re.search(a_pattern,a_text)
以open(a_file)作为fl:如果re.search(a_pattern,fl.read()):打印(“找到”)其他:print(“未找到”)
from string import ascii_letters
with open('text.txt') as fin :
text = fin.read()
text = ''.join( [i if in ascii_letters else ' ' for i in text] )
words = [i for i in text.split() if len(i) > 0]
words = set(words)
query = input( 'enter a word:' ).strip()
print query, 'is', '' if query in words else 'NOT', 'in the file'