python - 匹配模式并选择文件中的特定行

标签 python

下面显示了一个文本文件。我想仅选择 Class 10 block 下的 2 行(第 1 行和第 2 行)。

Thu May 29 14:16:00 PDT 2014
Class 09
line 0
line 1
line 2
--
Class 10
line 0
line 1
line 2
--
Class 11
line 0
line 1
line 2
--
Thu May 29 14:20:00 PDT 2014
Class 09
line 0
line 1
line 2
--
Class 10
line 0
line 1
line 2
--
Class 11
line 0
line 1
line 2
--

我已尝试以下操作,但 linecache 仅抓取第 1 行。我想找到一种方法先抓取line1,然后抓取line2。任何想法? 谢谢

numOflines = sum(1 for line in open('text.txt'))
print(num_lines)
for i in range(start,numOflines,step):  
    linea = linecache.getline('text.txt', i)
    print linea

最佳答案

numOflines = sum(1 for line in open('text.txt'))

这一行计算文件中的行数,仅此而已。可能不是您想要的。

不确定为什么您需要linecache。而且您没有显示如何计算 startstep,这可能是您的错误所在。

你想要的可能看起来像这样:

def reading_function():
    searching = True
    linesToRead = 2
    with open('text.txt') as f:
        for line in f:
            if searching and line.strip() == "Class 10":
                searching = False
            elif not searching:
                print line.strip()
                linesToRead -= 1
                if linesToRead == 0:
                    return

关于python - 匹配模式并选择文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24421889/

相关文章:

python - 按对象或两个 float 索引 python dict

python - 将旋转的 xticklabel 与其各自的 xticks 对齐

Python:使用 lambda 时,& 不支持的操作数类型: 'NoneType' 和 'NoneType'

python - 自动在文件夹中创建文件(Python)

python - 将 seq2seq NLP 模型转换为 ONNX 格式会对其性能产生负面影响吗?

python - 从本地目录使用 numpy

python - 用户身份验证如何在使用 Python 的 Google Sheets API 中进行?

python - 如何制作动态组合框PYQT5

python - 使用 Django/HTML/Python 不显示表单

Python doctests/sphinx : style guide, 如何使用它们并拥有可读的代码?