【问题标题】:Remove Same text from 2 text files从 2 个文本文件中删除相同的文本
【发布时间】:2019-01-11 23:43:03
【问题描述】:

Notepad++ 或 python

如果文本文件 1 有

,如何删除相同的行示例
 text123    
 text1234    
 text12345@    
 text12

和 textfile2 有

text123   
text 00   
text 001   
text 12  

输出为

text 00   
text 001

只需查找从 textfile1 到 textfile2 的重复行并输出为文本文件 1 中不存在的文本。

【问题讨论】:

  • 请将您的问题edit 发送至these standards
  • 输出将有 text 12 以及它与 text12 不同。
  • 你的意思是文件之间的匹配行,还是任何重复?

标签: python notepad++


【解决方案1】:

此解决方案避免将第二个文件的全部内容保留在内存中:

with open('textfile1.txt', 'r') as f:
    bad_lines = set(f.readlines())

with open('textfile2.txt', 'r') as f:
    for line in f.readlines():
        if not line in bad_lines:
            print(line)

【讨论】:

    【解决方案2】:
    with open('file1.txt','r') as f:
        for l in f:
            txt1.append(l)
    txt2 = []
    with open('file2.txt','r') as f:
        for l in f:
            txt2.append(l)
    ans = [line for line in txt2 if line not in txt1]
    print(ans)
    

    根据 ethans 评论更新:

    with open('file1.txt','r') as f:
        txt1 = f.readlines()
    txt2 = []
    with open('file2.txt','r') as f:
        for l in f:
            if l not in txt1:
                txt2.append(l)
    print(*txt2)
    

    【讨论】:

    • for l in f: txt1.append(l) 可以替换为txt1 = f.readlines() 并且txt1 可以从头开始删除。
    • @EthanK 感谢提醒
    • 另外,顶部的txt1 = [] 调用也不需要。
    【解决方案3】:

    您可以使用set 查找唯一条目:

    with open(file1) as f1:
      for line in f1:
        list1.append(line)
    
    with open(file2) as f2:
      for line in f2:
        list2.append(line)    
    
    print('unique elemets in f1 and not in f2 = {}'.format(set(list1) - set(list2)))
    print('unique elemets in f2 and not in f1 = {}'.format(set(list2) - set(list1)))
    

    【讨论】:

      【解决方案4】:

      您也可以为此使用pandas

      import pandas as pd
      
      df = df = pd.read_table(file1, names=['id'])
      df1 = df = pd.read_table(file2, names=['id'])
      
      df1[~df1.isin(df)].dropna()['id'].values.tolist()
      
      ['text 00', 'text 001']
      

      【讨论】:

        【解决方案5】:
        with open(file1) as f1, open(file2) as f2:
            for f1_line, f2_line in zip(f1, f2):
                if f1_line != f2_line:
                    print f2_line
        

        例如一个完整的工作示例:

        from io import StringIO
        
        f1 = StringIO("""text123
        text1234
        text12345@
        text12""")
        
        f2 = StringIO("""text123
        text 00
        text 001
        text 12""")
        
        for f1_line, f2_line in zip(f1, f2):
            if f1_line != f2_line:
                print(f2_line, end='')
        

        输出:

        text 00
        text 001
        text 12
        

        【讨论】:

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