在Python中查找txt文件中的字符串列表[复制]

时间:2021-04-17 20:43:54

This question already has an answer here:

这个问题在这里已有答案:

What is the fastest way to search a list of strings in a txt file in python?

在python中搜索txt文件中字符串列表的最快方法是什么?

I am loading the txt file, then splitting it's content by white spaces. It produces a list and then I am using : for eachString in StringList: if eachString in File: //do this

我正在加载txt文件,然后用空格分隔它的内容。它生成一个列表然后我正在使用:对于StringList中的eachString:如果File://中的eachString执行此操作

1 个解决方案

#1


0  

Assuming you want to know the location:

假设您想知道位置:

str.find(sub[, start[, end]])

str.find(sub [,start [,end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional

arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

参数start和end被解释为切片表示法。如果未找到sub,则返回-1。

If you don't care to know where the substring is located in the haystack string, just

如果您不想知道子串在干草堆字符串中的位置,只需

substr in haystack

will return True or False, and that's all you want to know

将返回正确或错误,这就是你想知道的全部

Since you're already loading the entire file into memory, this seems like the best way to go. If it turns out that the file is larger than will fit in memory, or is actually a stream, then some other approach will be required. (but I don't want to get into that unless it's needed)

由于您已经将整个文件加载到内存中,这似乎是最好的方法。如果事实证明文件大于适合内存的文件,或者实际上是一个流,那么将需要一些其他方法。 (但除非需要,否则我不想进入)

#1


0  

Assuming you want to know the location:

假设您想知道位置:

str.find(sub[, start[, end]])

str.find(sub [,start [,end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional

arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

参数start和end被解释为切片表示法。如果未找到sub,则返回-1。

If you don't care to know where the substring is located in the haystack string, just

如果您不想知道子串在干草堆字符串中的位置,只需

substr in haystack

will return True or False, and that's all you want to know

将返回正确或错误,这就是你想知道的全部

Since you're already loading the entire file into memory, this seems like the best way to go. If it turns out that the file is larger than will fit in memory, or is actually a stream, then some other approach will be required. (but I don't want to get into that unless it's needed)

由于您已经将整个文件加载到内存中,这似乎是最好的方法。如果事实证明文件大于适合内存的文件,或者实际上是一个流,那么将需要一些其他方法。 (但除非需要,否则我不想进入)