python - 从 3 个文本文件输出匹配行以及匹配行下的行

标签 python linux ubuntu

我有一个关于公共(public)数据的问题。我有三个文本文件,其中包含以下格式的数据:

    cli= 111
    mon= 45

    cli= 584
    mon= 21

    cli= 23
    mon= 417

现在我有以下程序,当我执行它时,它会为我提供所有匹配的 CLI。换句话说,它为我提供了出现在 3 个文本文件中的 CLI。

    with open ('/home/user/Desktop/text1.txt', 'r') as file1:
    with open ('/home/user/Desktop/text2.txt', 'r') as file2:
            with open ('/home/user/Desktop/text3.txt', 'r') as file3:
                    same = set(file1).intersection(file2).intersection(file3)
same.discard('\n')

with open ('/home/user/Desktop/common.txt', 'w') as file_out:
    for line in same:
            file_out.write(line)

我的问题是,我可以同时输出值 (MON= 45) 和 CLI= 111 吗?假设 CLI= 111 存在于所有 3 个文本文件中。我想要这样的结果:

    cli= 111
    mon= 45
    mon= 98
    mon= 32

提前致谢。 PS:以上示例数据仅为 1 个文本文件。假设有 3 个文本文件。谢谢!

最佳答案

看来您正在丢弃要稍后访问的数据。无需再次解析文件,您需要以某种方式捕获该数据,这样您就不会再次查看文件。一种方法(假设每个“cli”每个文件只有一个对应的“mon”)是使用字典。

我创建了一个函数,它根据提供的文件构建字典,其中键是“cli”数据,值是 mon 数据。从那里,您可以从字典键构建一个 Set() 并以这种方式找到交集。从交叉点,您知道返回值必须是字典中的键,所以只需将它们连接到一个“out”字符串并将其写入您的 out 文件:)

    def buildDict(f):
        dic = {}
        for i in range(0,len(f)):
            if "cli" in f[i]:
                dic[f[i]] = f[i+1]
        return dic

    with open ('1.txt', 'r') as file1:
        f1_dic = buildDict(file1.readlines())
        with open ('2.txt', 'r') as file2:
            f2_dic = buildDict(file2.readlines())
            with open ('3.txt', 'r') as file3:
                f3_dic = buildDict(file3.readlines())
                same = set(f1_dic.keys()).intersection(f2_dic.keys()).intersection(f3_dic.keys())

    out = ''
    for i in same:
        out += i
        out += f1_dic[i]
        out += f2_dic[i]
        out += f3_dic[i]


    with open ('common.txt', 'w') as file_out:
        file_out.write(out)

关于python - 从 3 个文本文件输出匹配行以及匹配行下的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37148539/

相关文章:

python - sendLine 不会发送整数(Twisted Python)

python - scikit-learn 中的机器学习算法是否必须将 pandas 数据帧转换为 numpy 数组

python - Django 1.11 get() 缺少 1 个必需的位置参数 : 'pk'

python - 将字符串转换为有序字典?

c++ - 如何在Linux上写一段程序让CPU忙到一定程度?

linux - Shell脚本不从输入文件中获取参数

linux - 找不到包 'libxml++-2.6'

ubuntu - Apache2 虚拟主机缺少文档根目录

php - 运行 Laravel 应用程序时在此服务器上找不到请求的 URL

ubuntu - 如何检查 Linux 内核上的默认 kvm mmu?