gpt4 book ai didi

python - 如何搜索文本文件中某一行的内容、替换该行并另存为新文件?

转载 作者:太空宇宙 更新时间:2023-11-03 20:27:51 25 4
gpt4 key购买 nike

我有一个 xml 文件,其中包含以下内容:

<supported-languages>
<lang><![CDATA[en_US]]></lang>
<lang><![CDATA[es_ES]]></lang>
<lang><![CDATA[de_DE]]></lang>
</supported-languages>

<2ndsupported-languages>
<lang><![CDATA[en_US]]></lang>
<lang><![CDATA[es_ES]]></lang>
<lang><![CDATA[de_DE]]></lang>
</2ndsupported-languages>

我只想删除任何包含 de_DE 的行,然后保存文件。

到目前为止我有这个:

import fileinput
import sys

file = "C:\\Users\Desktop\file.xml"
searchExp = "de_DE"
replaceExp = ""


def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)

replaceAll(file,searchExp,replaceExp)

接近,但并非如此。它将搜索“de_DE”,但只会将其替换为 <null> 。这是结果:

<supported-languages>
<lang><![CDATA[en_US]]></lang>
<lang><![CDATA[es_ES]]></lang>
<lang><![CDATA[]]></lang>
</supported-languages>

<2ndsupported-languages>
<lang><![CDATA[en_US]]></lang>
<lang><![CDATA[es_ES]]></lang>
<lang><![CDATA[]]></lang>
</2ndsupported-languages>

我希望我的结果看起来像这样

<supported-languages>
<lang><![CDATA[en_US]]></lang>
<lang><![CDATA[es_ES]]></lang>
</supported-languages>

<2ndsupported-languages>
<lang><![CDATA[en_US]]></lang>
<lang><![CDATA[es_ES]]></lang>
</2ndsupported-languages>

我该怎么做?

我尝试import re然后替换patternpattern = "^.*de_DE.*$"但这没有用。

最佳答案

仅写入不包含子字符串searchExp的行

def replaceAll(file, searchExp):
for line in fileinput.input(file, inplace=1):
if searchExp not in line:
sys.stdout.write(line)

关于python - 如何搜索文本文件中某一行的内容、替换该行并另存为新文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57700113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com