python - 如何搜索包含不同值的多行?
问题描述
我的长期目标是能够读取文件,并查找包含某个 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)
但这似乎不起作用。我也尝试创建一个列表,但似乎我可以使用列表。
解决方案
如果您想查找任何 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)
推荐阅读
- flutter - 在flutter中需要通过token将图片发送到服务器
- python - 无法绘制表格的频率分布
- android - 如何在 Jetpack Compose 的 OutlinedTextField 中显示错误消息
- googletest - 谷歌测试:寻找一个工作示例,将附加参数传递给被调用的函数
- javascript - 猜数字 - 猜猜限制
- php - 取消链接 filePath Laravel Php 中的上传文件夹
- javascript - 如何将布尔字符串转换为布尔值?
- typescript - 打字稿:联合类型字段的约束
- r - 如何用 3 列矩阵制作方阵?使用 R
- javascript - 有谁知道如何在 nodejs 中从 X 行到 Y 行读取文件?