【问题标题】:searching string on two text files using python使用python在两个文本文件上搜索字符串
【发布时间】:2018-12-05 20:48:43
【问题描述】:

使用python,如何处理两个文本文件。 例如:a.txt 有 5 个组,b.txt 也有 4 个组。 b.txt 将查找 a.txt 上可用的组。如果找到,将其写入 output.txt,如果未找到,则不要将其写入 output.txt。 组中的数字应该匹配,但顺序并不重要。

一个.txt

GROUP :[11111, 22222, 33333]
GROUP :[22222, 11111]
GROUP :[46098]
GROUP :[66666, 55555, 44444]
GROUP :[55555, 44444]

b.txt

GROUP :[11111, 33333]
GROUP :[46098]
GROUP :[22222, 11111]
GROUP :[44444, 55555, 66666]

输出.txt

GROUP :[22222, 11111]
GROUP :[46098]
GROUP :[44444, 55555, 66666]

【问题讨论】:

    标签: python string search


    【解决方案1】:

    不是世界上最漂亮的东西,但应该完成工作:

    from collections import Counter
    
    with open('a.txt', 'r') as a:
        a_list = []
        for line in a:
            groups = line.split(':')[1]
            groups = groups.split('[')[1].split(']')[0]
            groups = groups.split(', ')
            a_list.append(groups)
    
    with open('b.txt', 'r') as b:
        b_list = []
        for line in b:
            groups = line.split(':')[1]
            groups = groups.split('[')[1].split(']')[0]
            groups = groups.split(', ')
            b_list.append(groups)
    
    with open('output.txt', 'w') as output:
        a_counter = [Counter(i) for i in a_list]
        for group in b_list:
            if Counter(group) in a_counter:
                output.write(f"GROUP :{group}\n")
    

    【讨论】:

    • 非常感谢,您能解释一下您的代码吗?如果你不介意?
    【解决方案2】:

    使用正则表达式和重新模块:

    import re
    
    grp_tmpl = list()
    
    # Register all groups
    f = open('b.txt', 'r')
    for line in f.readlines():
        grp_tmpl.append(sorted(re.findall('\d+', line)))
    
    # Find groups
    out = open('output.txt', 'w')
    f = open('a.txt', 'r')
    for line in f.readlines():
        for t in grp_tmpl:
            if t == sorted(re.findall('\d+', line)):
                out.write(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      相关资源
      最近更新 更多