【问题标题】:How to parse specific lines of data in Python如何在 Python 中解析特定的数据行
【发布时间】:2022-01-04 05:25:25
【问题描述】:

我有一个包含多行数据的文本文件。每行以“# Source [number]”结尾。可能有多个来源,例如“# Source 1,3”。

文本示例:

This is line one   # Source 3
This is line two   # Source 2
This is line three # Source 4,5
This is line four  # Source 5
This is line five  # Source 2

问题: 我怎样才能只解析感兴趣的来源的行。我想获取源代码 4 及更高版本中的行。结果应该是一个列表或字典,如下所示:

This is line three
This is line four

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 请提供输入和预期结果。这可能是正则表达式的情况,为了帮助您,我们需要确切地知道您的期望。例如,如果您正在寻找 # Source 5,是否包含 # Source 4,5,或者它必须与感兴趣的来源完全匹配。
  • 在逐行读取文件时尝试使用str.split,以#为分隔符。

标签: python-3.x


【解决方案1】:

略微过度设计,但完全按照您想要的方式工作

import re

subject = """This is line one   # Source 3
This is line two   # Source 2
This is line three # Source 4,5
This is line four  # Source 5
This is line five  # Source 2
"""

matches = re.findall(r"[Source\s][\d(,)]{1,}", subject)
matches = list(map(lambda x: int(x) if not "," in x else list(map(int, x.split(","))), matches))
matches = list(map(lambda y: y if isinstance(y, int) else max(y), matches))

subject_lines = subject.splitlines()
subject_lines = list(map(lambda z: z[0], list(map(lambda q: q.split("#"), subject_lines))))

for index, each_source_value in enumerate(matches):
    if each_source_value >= 4:
        print(subject_lines[index])

输出:

This is line three 
This is line four 

并且也适用于具有类似条件的其他主题字符串。

【讨论】:

    【解决方案2】:

    此代码将根据输入给出的值选择行:

    number = input("Get lines for source higher or equal than: ")
    
    result = []
    
    with open("D:/data.txt") as f:
        for line in f:
            phrase, comment = line.split("#")
    
            for item in comment.replace(",", " ").split():
                try:
                    if int(item) >= int(number):
                        result.append(phrase.strip())
                        break
                except ValueError:
                    pass
    
    print(result)
    

    对于输入值4,这将输出:

    ['This is line three', 'This is line four']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2018-01-01
      • 1970-01-01
      • 2015-04-06
      • 2014-09-15
      相关资源
      最近更新 更多