繁体   English   中英

在文本文件中的行之间读取

[英]Read between lines in text file

首先,我的示例文本文件的内容如下所示:

Some Data
Nothing important
Start here
This is important
Grab this line too
And this ono too
End here
Text goes on, but isn't important
Next text
Blaah

现在,我想读入文本文件,并且只想在“ 从这里开始 ”和“ 从这里 结束 ”之间抓线。

所以我的Python代码看起来像:

filename = 'example_file.txt'

with open(filename, 'r') as input:
   for line in input: # First loop breaks at specific line
       if 'Start here' in line:
           break

   for line_1 in input: # Second loop grabs all lines
       print line_1.strip()

   for line_2 in input: # Third loop breaks at specific line
       if 'End here' in line_2:
           break

但这是行不通的。

这是我运行时的输出:

This is important
Grab this line too
And this on too
End here
Text goes on, but isn't important
Next text
Blaah

如您所见,我的脚本没有在End here中断。 程序从正确的行开始,但没有在正确的行中断。

怎么了?

这是需要休息的第二个循环...

for line_1 in input:
    if 'End here' in line_1:
        break
    print line_1.strip()

您的问题是您应该在第二个循环中检查“ End Here”,因为第二个和第三个循环不会同时运行。 实际上,第三个循环甚至不会运行。

考虑到这一点,此代码将起作用:

filename = 'mydata.txt'

with open(filename, 'r') as f:
    for line in f:
        if 'Start here' in line:
            break

    for line_1 in f:
        if 'End here' in line:
            break
        else:
            print line.strip()

但是,我们仍然可以进行一些优化:

  • for循环上的变量仅是for循环的局部变量,因此我们可以重用该名称;
  • break后的任何代码都不会运行,因此我们可以摆脱else
  • open默认情况下使用读取模式。

考虑到这一点,您的最终代码将如下所示:

filename = 'mydata.txt'

with open(filename) as f:
    for line in f:
        if 'Start here' in line:
            break

    for line in f:
        if 'End here' in line:
            break
        print line.strip()

运行它,您将获得所需的输出:

This is important
Grab this line too
And this ono too

您可以使用带有re.DOTALL选项的正则表达式( re模块),以便将换行符视为正则字符。

import re

source = """Some Data
Nothing important
Start here
This is important
Grab this line too
And this ono too
End here
Text goes on, but isn't important
Next text
Blaah"""

# or else:
# source = open(filename, 'r').read() # or similar

result = re.search("Start here(.*)End here", source, re.DOTALL).group(1).strip()

print result

> This is important
> Grab this line too
> And this ono too

工作原理:

  • re.search在某些字符串中寻找模式;
  • 括号将匹配项分组 第一组是整个模式,第二组是括号。 组可以排序和嵌套;
  • .*表示“任何字符,任何次数”。 需要在两个硬编码的标记之间进行所有操作(即Start HereEnd here );
  • re.DOTALL是个秘密:它将换行符视为常规字符串字符。 点是“任何字符”的符号,因此“全部点”的意思是“将任何字符作为常规字符,甚至换行字符进行处理”。
  • group(1)表示您想要第二个(从零开始的索引)组,它是括号内的组。

您可以先阅读所有行并进行枚举:

filename = 'example_file.txt'

useful_content = []
with open(filename, 'r') as input:
    all_lines = input.readlines()  # read all lines
    for idx in range(len(all_lines)):  # iterate all lines
    if 'Start here' in all_lines[idx]:
        useful_content.append(all_lines[idx].strip())
        idx = idx + 1
        # found start of useful contents, continue iterate till it ends
        while 'End here' not in all_lines[idx]:
            useful_content.append(all_lines[idx].strip())
            idx = idx + 1
        break
for line in useful_content:
    print(line)

暂无
暂无

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

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