Python替换文件中的匹配内容 [英] Python replace matching contents in a file

查看:305
本文介绍了Python替换文件中的匹配内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望与文本文件进行比较,并用空格替换匹配的文本。我的文件看起来像这样,



文件1



L1 Abc

L2 HHS

L3 RTY

L4 TYU

L5 678



文件2



L1 Abc

L2 HHS

L3 RTY

L4 TYU

L5 678

L6 HTY

L7 KYU

L8 POI



我需要比较文件1和文件2,然后替换文件1中的匹配内容以替换为空格。



我写了以下代码Python但它没有取代值。我怎样才能得到理想的结果。我应该使用不同的方法吗?请指教...



在此先感谢。



我尝试了什么:



I am looking to compare to text files and replace matching texts with blanks. My files look like this,

File 1

L1 Abc
L2 HHS
L3 RTY
L4 TYU
L5 678

File 2

L1 Abc
L2 HHS
L3 RTY
L4 TYU
L5 678
L6 HTY
L7 KYU
L8 POI

I need to compare file 1 and file 2 and then replace matching contents in File 1 to be replaced with blanks.

I have written the following code in Python but its not replacing the values. How can I get the desired results. Should I use different approach ? Please advise...

Thanks in Advance.

What I have tried:

import re


newcontent: str=''
oldcontent: str=''

with open('C:\Temp\\test1.log', 'r') as content_file:
    newcontent = content_file.read()
    #print(newcontent)


def replaceData(txt):
    with open('C:\Temp\\test2.log', "r") as fout:
        oldcontent = fout.read()
        print(oldcontent)

    print('end of old content....')

    a=txt.replace(oldcontent,'')
    print(a)

replaceData(newcontent)

推荐答案

您正在尝试替换第一个文件中出现的第二个文件的完整文本。但该文本不存在于第一个文件中,只存在于其中的一部分。您应该逐行读取第二个文件,并尝试替换该行的文本。类似于:

You are trying to replace the complete text of the second file that occurs in the first. But that text does not exist in the first file, only a part of it. You should read the second file line by line and try the replace on just the text of that line. Something like:
import re

newcontent: str=''
oldcontent: str=''

with open('C:\Temp\\test1.log', 'r') as content_file:
    newcontent = content_file.read()
    #print(newcontent)


def replaceData(txt):
    with open('C:\Temp\\test2.log', "r") as fout:
        for line in fout:
            txt=txt.replace(line,'')

replaceData(newcontent)


类似于

Something similar to
with open("test1.log") as f:
    f1lin = f.readlines()

with open("test2.log") as f:
    f2lin = f.readlines()

f3lin = [s for s in f2lin if not (s in f1lin)]
with open("test3.log", "w+") as f:
  f.writelines(f3lin)

我想。


这篇关于Python替换文件中的匹配内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆