首页 > 解决方案 > 如何搜索包含不同值的多行?

问题描述

我的长期目标是能够读取文件,并查找包含某个 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)

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

标签: pythonpython-3.x

解决方案


如果您想查找任何 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语句,因为它会在with块之后关闭文件-您忘记了。我命名了变量id_,而不是id因为我不想覆盖 builtin 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)

推荐阅读