首页 > 解决方案 > Python:在两个文件中查找字符串并打印所有行

问题描述

我需要从另一个文件中找到一个事件。

我的文件是这样的:

文件 1:CLUSTER_NAME

文件 2:时间戳、集群名称、日志

我想要的是检查第一个文件中的集群是否甚至在第二个文件中并打印所有行。

例如:

文件1:

文件2:

输出应该是这样的

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("_______________")

它有效,但我需要打印所有日志。我不知道如何链接我的操作结果来打印我需要的东西。

标签: pythonpandas

解决方案


使用正则表达式

  • 这个简单的文件读取不需要 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

推荐阅读