gpt4 book ai didi

python - 从linux中的字符串列表中扫描数据

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:00 25 4
gpt4 key购买 nike

我有两个文件:

  • file_a = 字符串列表
  • file_b = data {或者 file_b 可以是所有这些文件所在的目录}

完成以下任务的最佳选择是什么:

{保存输出}扫描并显示在 file_b 中找到的所有行,其中包含在 file_a 中找到的至少 1 个字符串。

例如 file_a 包含以下字符串(在我的例子中,列表很长)

01101

11001

11101

文件_b

01101:11100:10001

11111:11100:10001

01111:11100:11001

11101:11111:11110

根据此示例,第 1 行、第 3 行和第 4 行确实包含字符串

最佳答案

您可以使用 open 方法中文件句柄的 readlines() 方法读取两个文件的行,并迭代每一行以查找 file_a 的字符串是否与 line_b 中的字符串相交。由于您尚未向我们提供有关您的文件格式以及您迄今为止所做的操作的更多信息,因此我将仅提供伪代码。

with open('file_a','r') as f1:
strings=f1.readlines() #note I suppose each string is on one line

with open('file_b','r') as f2:
lines=f2.readlines()

# iterate to find intersection of strings in line
for line in lines:
tmp=line.strip()
print list(set(strings) & set(line))

参见Find intersection of two nested lists?对于 2 个列表的交集

关于python - 从linux中的字符串列表中扫描数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com