【问题标题】:Python: how to get the related lines from file?Python:如何从文件中获取相关行?
【发布时间】:2017-01-26 15:50:07
【问题描述】:

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

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循环?用于线路...? “相关”是指包含批量单词的行
  • 所以你需要找到a.txt中的行与b.txt中的行完全相同?
  • 我认为您的第一个问题是您对变量名称产生了很多混淆。 lines_batch 是没用的,因为你从来没有往里面放任何东西,而bigstat 包含整个文件作为一个字符串,而不是一个列表,所以你的条件非常低效。

标签: python file search printing strip


【解决方案1】:

这里有一些代码只使用一个 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())

编辑:

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

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

i 为您获取 read_file 中的行号。
a_lines[i] 为您获取相应的列表项(= 行的内容)
b_lines.index(line) 为您获取项目的编号 @ b_lines 列表中的 987654329@(= batch_file 中的行号)
line.strip() 为您获取 batch_file 中该行的内容,不带尾随 \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())

【讨论】:

  • 非常感谢!它真的对我帮助很大!我可以问你另一个问题:我怎样才能得到包含该行的 a_lines 。我尝试使用 str.find 和 str.index ,它们都只是给了我位置......
  • 嘿,不客气!我在原始答案中添加了一些代码,这些代码应该向您展示如何不仅获取每行的内容,还可以获得每行的数量。如果您的问题得到解决,您将我的答案标记为已接受,我将不胜感激!只需点击左侧的绿色复选标记即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 2015-02-08
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 2014-04-19
  • 1970-01-01
相关资源
最近更新 更多