python - Python:在两个文件中查找字符串并打印所有行
问题描述
我需要从另一个文件中找到一个事件。
我的文件是这样的:
文件 1:CLUSTER_NAME
文件 2:时间戳、集群名称、日志
我想要的是检查第一个文件中的集群是否甚至在第二个文件中并打印所有行。
例如:
文件1:
- 集群A,
- 集群B,
- 集群C,
文件2:
- 2019,集群B,日志
- 2020, 集群C, 日志
- 2017,clusterZ,日志
输出应该是这样的
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("_______________")
它有效,但我需要打印所有日志。我不知道如何链接我的操作结果来打印我需要的东西。
解决方案
使用正则表达式
- 这个简单的文件读取不需要 Pandas。
代码
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
输出
2019, clusterB, log
2017, clusterZ, log
推荐阅读
- time-series - 如何移动 df 的几列,每列具有特定的滞后
- c# - 在一个序列中找到一个 1 的簇
- python - 卸载并重新安装 numpy 包后无法使用 numpy 方法
- python - 您正在尝试将包含 36 层的权重文件加载到具有 19 层的模型中
- google-chrome-extension - 谷歌浏览器扩展 - 上传新包时出现明显错误
- ios - iOS - best practice to wait for protected data become available?
- c# - How can I get the data from the last week on the chart by pressing a button?
- python - How do I draw a line on top of a cv2 generated image?
- javascript - 在角度材料中禁用带有假期列表和工作日(周六和周日)的 mat-datepicker
- c++ - 实数和双数的区别