![](/img/trans.png)
[英]Python how to find any or all strings-list in a line and then print the exact string found
[英]Python: Find strings in two file and print all the line
我需要从另一个文件中找到一个事件。
我的文件是这样的:
文件 1:CLUSTER_NAME
文件 2:时间戳、集群名称、日志
我想要的是检查第一个文件中的集群是否甚至在第二个文件中并打印所有行。
例如:
文件1:
文件2:
Output 应该是这样的
Input: clusterB, clusterZ
output: 2017, clusterZ, log
2019, clusterB, log
import pandas as pd
#ARRAY
my_value = []
cluster_value = []
#READ THE FILES
my_data_file = pd.read_csv('my_data.txt', sep=',')
log_file = pd.read_csv('log.txt', sep=',')
#TAKE THE COLUMN WITH THE CLUSTERS
for row in my_data_file[my_data_file.columns[1]]:
my_value.append(row)
for row in log_file[log_file.columns[0]]:
cluster_value.append(row)
#Restult
print("_______________")
print(list(set(my_value) & set(cluster_value)))
print("_______________")
它有效,但我需要打印所有日志。 我不知道如何链接我的操作结果来打印我需要的东西。
使用正则表达式
代码
import re
def search(key_file, search_file):
with open(key_file) as kfile:
keys = '|'.join(line.rstrip().split(',')[0] for line in kfile.readlines())
# regex for cluster names
regex = re.compile(keys)
with open(search_file) as search_data:
for line in search_data:
if regex.search(line):
print(line.rstrip())
search('mydata.txt', 'log.txt')
输入
'mydata.txt' (注意 ',' 无关紧要,即被忽略)
clusterB,
clusterZ
'日志.txt'
2019, clusterB, log
2020, clusterC, log
2017, clusterZ, log
Output
2019, clusterB, log
2017, clusterZ, log
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.