【问题标题】:How can I search multiple lines that contain different values?如何搜索包含不同值的多行?
【发布时间】:2021-02-08 09:16:29
【问题描述】:

我的长期目标是能够读取文件,并查找包含某个 Id 的多行并从这些行中提取数据。现在我正在尝试查找包含这些特定 ID 的某些行并打印这些行,以便我知道我有正确的数据。

每一行都以 {"id": "101" 开头,它有不同的 ID 号,但它也有一个很长的记录号,并且在任何记录号中都可以包含一些 ID 号,所以我正在搜索“”id #" " 如下所示。

handle = open('info.txt')
for line in handle:
    if not '"101"' in line:
        continue
    print(line)

上面的代码有效,但如果我想提取多个值,例如 101 110 170 230,我想尝试这样的操作。

handle = open('info.txt')
for line in handle:
    if not '"101"' '"110"' '"170"' '"130"' in line:
        continue
    print(line)

但这似乎不起作用。我也尝试创建一个列表,但似乎我可以使用列表。

【问题讨论】:

  • 请展示info.txt中数据的一个小例子(3或4行就够了)。

标签: python python-3.x


【解决方案1】:

如果您想查找任何 ID,请使用 any

ids = ['101', '110', '120', '170', '130']

with open('info.txt') as handle:
    for line in handle:
        if not any(id_ in line for id_ in ids):
            continue
        print(line)

我使用了with 语句,因为它会在withblock 之后关闭文件——你忘记了。我将变量命名为id_ 而不是id,因为我不想覆盖内置的id

既然您说过“每一行都以{"id": "101" 开头,并且它有不同的 ID 号”,您可能不仅想检查 id 是否在行中的某个位置,还想检查该行是否以此序列开头。

with open('info.txt') as handle:
    for line in handle:
        if not any(line.startswith(f'{{"id": "{id_}"') for id_ in ids):
            continue
        print(line)

【讨论】:

    【解决方案2】:

    你想要类似的东西

    valid_values = ['"101"', '"110"', '"170"', '"130"']
    
    for line in handle:
        if not any(value in line for value in valid_values):
            continue
        print(line)
    

    首先,您在一个易于访问的列表中定义有效值。然后,any 函数依次检查每一行的每个值

    【讨论】:

      【解决方案3】:

      问题出在这一行:

      if not '"101"' '"110"' '"170"' '"130"' in line:
      

      在 Python 中用空格分隔字符串是一种连接形式,其计算结果如下:

      if not '"101""110""170""130"' in line:
      

      正如您可能想象的那样,它永远不会被发现。相反,您需要的是一个辅助函数,它将遍历您的 id 列表:

      id_list =  ['"101"', '"110"', '"170"', '"130"']
      
      def id_in_line(line):
         for id in id_list:
            if id in line:
                return True
          return False
      
      handle = open('info.txt')
      for line in handle:
          if not id_in_line(line):
              continue
          print(line)
      

      【讨论】:

        【解决方案4】:

        你可以使用any(),即:

        m = ["101", "110", "170", "130"]
        
        with open("info.txt") as f:
          for l in f:
            if not any(v in l for v in m):
              continue
            print(l)
        

        Demo

        【讨论】:

        • 只是一个小提示:没有必要在any([v in l for v in m]) 中建立一个列表。使用这种方法,您必须在检查any 之前构建整个列表。使用带有any(v in l for v in m) 的生成器。如果找到项目,这将停止评估。
        • 你是对的,这是列表理解的习惯,现在更正了。谢谢
        【解决方案5】:

        您可以使用json 库来做到这一点! json.loads() 函数应该可以完成这项工作!为了查看数据,您应该能够执行以下操作:

        for id in data.keys():
            if id == '123455789':
                #do something
        

        【讨论】:

        • 你怎么知道文件是 JSON 格式的?
        • 单从这一点来看:“每一行都以{“id”:“101”开头,”,它似乎只是一个普通的dict? 对不起,如果我在这里出错了
        • 可能是。也许不会。如果它真的是 JSON,那么你的方法很好。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 2019-07-26
        相关资源
        最近更新 更多