gpt4 book ai didi

python - 排序一个巨大的文本文件并进行二进制搜索

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:06:37 26 4
gpt4 key购买 nike

假设一个带有文本信息的巨大文件 -

内容

"Hello, How are you?
This is Bob
The contents of the file needs to be searched
and I'm a very huge file"

搜索字符串

 Bob

现在我需要在文件中搜索单词“Bob”并进行二进制搜索。我该怎么做?

我尝试使用 UNIX SORT 对文件进行排序,我得到了以下输出 -

and I'm a very huge file
How are you?
The contents of the file needs to be searched
This is Bob

它对文件进行排序,但“Bob”一词位于最后一行。

这个问题是搜索“我没有搜索整行”而不是文件中的单个单词..

执行此操作的最有效方法是什么?

最佳答案

最有效的方法是创建一个生成器,生成单个单词,然后将它们与您要查找的单词进行比较。

def get_next_word():
with open("Input.txt") as in_file:
for line in in_file:
for word in line.strip().split():
yield word

print any(word == "Bob" for word in get_next_word())
# True

我们使用 any 函数,它在找到匹配项时短路。因此,我们不必处理整个文件。

编辑:

如果您要多次搜索,最好的方法是将单词列表转换为一个集合,然后使用 in 运算符检查单词是否存在。

words_set = set(get_next_word())

print "Bob" in words_set
# True
print "the" in words_set
# True
print "thefourtheye" in words_set
# False

关于python - 排序一个巨大的文本文件并进行二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22469715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com