繁体   English   中英

Python:如何从文件中获取相关行?

[英]Python: how to get the related lines from file?

如何从文件中获取相关行? 这是我的代码:

read_file = "a.txt"  
read_batch = "b.txt"      

lines_batch = list()
with open(read_file) as r:
    bigstat = r.read()

with open(read_batch) as b:
    for batch in (line_batch.strip() for line_batch in b):
        if batch in bigstat:
            print(???)

Bigstat 是一个有 50 行的 txt,但我只想要其中的 2 个,其中包含批处理。

我该怎么办? 十分感谢你的帮助!!!!!!

这是一些仅使用单个 for 循环和单个 if 语句来检查 read_file 中的一行是否存在于 batch_file 中的代码(我假设这就是您要检查的内容!)。

只需打开文件并使用readlines()分别获取所有行。 然后只需遍历 read_file 中的所有行并检查它们是否在 batch_file 中的行列表中(注意 readlines() 生成一个列表,其各个条目是每行的内容,包括结尾的\\n字符)。

read_file = "a.txt" 
batch_file = "b.txt" 

with open(read_file) as a: 
    a_lines = a.readlines() 

with open(batch_file) as b: 
    b_lines = b.readlines() 

for line in a_lines: 
    if line in b_lines: 
        print(line.strip())

编辑:

要获得包含与batch_file 中的行匹配的read_file 中的行号,您必须更改浏览read_file 的方式。 在这种情况下,使用enumerate不仅可以获取每行的内容,还可以获取每行的编号(在这种情况下存储在变量i )。

然后我只打印了 read_file 和 batch_file 中匹配行的数量和内容。

i您获取 read_file 中的行号。
a_lines[i]您提供相应的列表项(= 行的内容)
b_lines.index(line)获取b_lines列表中项目lineb_lines (= b_lines中的行数)
line.strip()获取line.strip()中该行的内容,不带尾随\\n字符。

请参阅随附的扩展代码:

read_file = "a.txt" 
batch_file = "b.txt" 

with open(read_file) as a: 
    a_lines = a.readlines() 

with open(batch_file) as b: 
    b_lines = b.readlines() 

for i, line in enumerate(a_lines):
    if line in b_lines:
        print("Number of line in read_file is %i" % i)
        print("Content of line in read_file is %s" % a_lines[i].strip())

        print("Number of line in batch_file is %i" % b_lines.index(line))
        print("Content of line in batch_file is %s" % line.strip())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM