python - 匹配文件中的行,例如 grep -f

标签 python design-patterns matching

我试图在两个大文件中查找匹配的行,就像 grep -f 一样。
假设文件 f.txt 包含 3 行:

1  
2  
3  

文件 g.txt 包含 3 行:

3  
4  
5  

我想打印匹配的行:

3

这是我尝试过的:

f=open('f.txt', 'r')  
g=open('g.txt', 'r')  
i=0  
for line in f:  
    search = g.readlines()[i]  
    if line.strip() == search :  
        print line  
    i += 1

这会返回错误

'AttributeError: 'file' object has no attribute 'split'

最佳答案

您将需要读取包含要匹配到内存中的行的文件;否则,您将必须阅读正在搜索的整个文件,以查找包含搜索词的文件的每一行。我们将使用 set 来完成此操作,因为检查 set 中是否有某些内容的速度非常快。

with open("f.txt") as f:
    terms = set(line.strip() for line in f)

with open("g.txt") as g:
    for line in g:
       line = line.strip()
       if line in terms:
           print line

在这种情况下,您将哪个文件视为包含搜索词的文件以及将哪个文件视为您正在搜索的文件并不重要,因为您只是在查找匹配项。为了最大限度地减少内存使用,您可以选择较小的一个 f

关于python - 匹配文件中的行,例如 grep -f,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34644161/

相关文章:

python - 错误消息堵塞 Telethon 导致安全错误 : Server sent a very new message xxxxx was ignored

python - Pickle 和装饰类(PicklingError : not the same object)

java - "Realtime"中多用户编辑的软件设计模式

design-patterns - 我什么时候需要停止使用设计模式?

design-patterns - 丰富的领域模型和 ORM

database - 为 500,000 个用户存储权重对的最佳方式?

python - 如何查找文本文件中是否包含整个单词?

python - tkinter:如何制作不使用 winico 的系统托盘应用程序?

mysql - 在 MySQL ListOfValues 中查询匹配项

linux - Grep 用另一个过滤一个文本文件(非常大的文件)