在文件中查找字符串的最快方法 [英] The fastest way to find a string inside a file
问题描述
我尝试了多种在文件中查找字符串的方法,但都很慢.我只需要:
I have tried many ways of looking for a string inside a file, but all were slow. All I need is:
- 在文件中查找字符串
- 打印字符串所在的行
到现在为止我所做的只是读取文件(尝试了很多方法)然后检查我要查找的字符串是否位于当前行中.如果不是,请检查下一行等
All I've been doing until now was reading a file (tried many ways) and then checking whether the string I am looking for is located in the current line. If not, check the next line, etc.
这样做的最佳方法是什么?
推荐答案
以下将适用于子字符串 something
的第一次出现.None
如果没有找到匹配,则赋值;文件被延迟读取到第一个匹配项.
The following will work for the fist occurrence of a substring something
. None
is assigned if no match is found; file is read lazily up to the first match.
with open('input.txt') as f:
line = next((l for l in f if something in l), None)
要查找所有匹配项,您可以使用列表推导式:
To find all matches, you can use a list comprehension:
with open('input.txt') as f:
lines = [l for l in f if something in l]
我不知道你在纯 python 中是否可以比这快得多.
I do not know if you can be much faster than this in pure python.
这篇关于在文件中查找字符串的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!