【问题标题】:Compare two text files, replace lines in first file that contain a string from lines in second file比较两个文本文件,替换第一个文件中包含第二个文件行中的字符串的行
【发布时间】:2017-04-20 12:44:52
【问题描述】:

我正在尝试用 file2 中的更正值替换 file1 中存在“错误”的行(见下文)。

文件1:

MAGA 0.0159
TTKI error
MCCN 0.0391
NEFD 0.9982
ESYA error

文件2:

TTKI 0.7652
ESYA 0.5517

期望的输出:

MAGA 0.0159
TTKI 0.7652
MCCN 0.0391
NEFD 0.9982
ESYA 0.5517

以下是我一直在尝试的方法,但我认为我已经走了很远,并且在过去一个小时左右变得越来越沮丧,所以任何帮助都将不胜感激。

section2 = []

f2 = open('file2', 'r')

for line2 in f2:
    section2.append(str(line2.split(' ',0)))

f1 = open('file1', 'r')

for line1 in f1:
    if str(section2[0]) in line1:
        print section2[0]
    else:
        print line1

【问题讨论】:

    标签: python string text


    【解决方案1】:

    您可以创建一个具有正确值的dict

    dict2 = {}
    for line in f2:
       key, value = line.split(' ')
       dict2[key] = value
    

    然后

    for line1 in f1:
        key, value = line1.split(' ')
        if value == 'error':
            print(key, dict2[key])
        else:
            print(line1)
    

    【讨论】:

      【解决方案2】:

      这是一个简单的逻辑:

      打开第二个文件并从中创建一个字典。 读取 file1 行/行 在线搜索错误, 如果找到 获取错误行的第一个字 从字典中得到对应的值 用你得到的值替换错误 将行写入第三个文件

      【讨论】:

        【解决方案3】:

        使用字典而不是数组:

        corrections = {}
        
        f2 = open('file2.txt', 'r')
        
        for line2 in f2:
            (key, value) = line2.split(' ')
            corrections[key] = value
        
        f1 = open('file1.txt', 'r')
        
        for line1 in f1:
            (key, value) = line1.split(' ')
            if key in corrections:
                print(key, corrections[key])
            else:
                print(line1)
        

        这是您的字典在读取更正文件后的样子:

        {'TTKI': '0.7652', 'ESYA': '0.5517'}
        

        file1 被读取时,这些行也会被拆分,只是为了检查第一个值是否是字典中的一个键(key in corrections)。如果不是,则仅打印原始行(即使它包含error)。但如果我们有更正,则会打印出来 (print (key, corrections[key])。这里我们使用 print 在其参数之间插入一个空格这一事实。

        【讨论】:

          【解决方案4】:
          file1 = 'f1.txt'
          file2 = 'f2.txt'
          with open(file1, 'r') as file:
              file1data = file.read()
          with open(file2, 'r') as file:
              file2data = file.read()
          
          x = file1data.split('\n')
          y = file2data.split('\n')
          
          for i in x:
             for j in y:
                if i[:4] == j[:4]:
                   file1data = file1data.replace(i,j)
          
          with open(file1, 'w') as file:
             file.write(file1data)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-05-01
            • 1970-01-01
            • 2013-04-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-07-06
            • 1970-01-01
            相关资源
            最近更新 更多