【问题标题】:Print only lines after certain lines in Python仅在 Python 中某些行之后打印行
【发布时间】:2019-09-05 18:29:33
【问题描述】:

例如,我有一个包含很多行的 csv 文件

This is line 1
This is line 2 
This is line 3 
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9

使用 Python 中的代码,我只需要打印某些行之后的行,更具体地说,我需要打印第 3 行之后的行和第 7 行之后的行,并且在打印之后,需要打印把它们放在另一个 csv 中。

我该怎么做? 谢谢!!

【问题讨论】:

标签: python csv web-scraping


【解决方案1】:

您可以遍历文件中的行并在找到匹配项时返回。像这样的:

def find_line_after(target):
    with open('lines.csv', 'r') as f:
        line = f.readline().strip()
        while line:
            if line == target:
                return f.readline().strip()
            line = f.readline().strip()

【讨论】:

    【解决方案2】:

    如果您可以合理地预测行可能包含的内容,那么使用正则表达式将是我的首选解决方案。

    import re
    
    re_pattern = re.compile(r"This is line [37]")
    # The above is used to match "This is line " exactly, followed by either a 3 or a 7.
    # The r before the quotations mean the following string should be interpreted literally.
    
    output_to_new_csv = []
    print_following_line = False
    for line in csv_lines:
        if print_following_line:
            print(line)
            output_to_new_csv.append(line)
        print_following_line = False
        if re.match(re_pattern, line):
            print_following_line = True
    
    # Then write output to your new CSV
    

    代码最初将 print_following_line 设置为 False,因为您不知道是否要打印下一行。如果您的正则表达式字符串与当前行匹配,您的 print_following_line 布尔值将设置为 True。然后它将打印下一行并将其添加到您的输出列表中,您可以稍后将其写入 CSV。

    如果您是正则表达式的新手,这个网站对于调试和测试匹配非常有帮助:https://regex101.com/

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 2013-02-12
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多