我正在帮助将旧技术文档从我的旧公司迁移到新公司。我需要删除像这样的旧公司引用: ABC 部门名称 产品名称 到 产品名称。
也可以是 部门名称 产品名称 到 产品名称。
技术文档的旧名称也改为新名称: 技术文档到新文档名
我发现一些脚本可以一次执行 1 个操作。然后我找到了一个 glob 脚本,它可以同时执行多个文件,进行 1 次更改。
我发现一些脚本可以一次更改 1 个 xml 文件。 然后我找到了一个 glob 脚本,它可以同时执行多个文件并进行 1 次更改。
import glob
import ntpath
import os
output_dir = "output"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for f in glob.glob("*.xml"):
with open(f, 'r', encoding='utf-8') as inputfile:
with open('%s/%s' % (output_dir, ntpath.basename(f)), 'w', encoding='utf-8') as outputfile:
for line in inputfile:
outputfile.write(line.replace('OldCompanyName ProductName', 'ProductName'))
我的目标是将两个旧产品名称更改为新名称。 line.replace 是最好的方法吗? 如果是这样,我可以做“ABC Divisionname ProductName”| “部门名称”、“产品名称”?
最佳答案
您可以使用正则表达式替代方法[ re.sub ] 下面是一个可能有帮助的示例。
import re
sample_xml_data = 'ABC Divisionname ProductName is the company name'
sample_xml_data_1 = 'Divisionname ProductName is the company name'
# Here is your pattern
old_company_name_pattern = re.compile('ABC Divisionname ProductName|Divisionname ProductName')
new_company_name = 'ProductName'
print(re.sub(old_company_name_pattern,new_company_name,sample_xml_data))
print(re.sub(old_company_name_pattern,new_company_name,sample_xml_data_1))
output :
ProductName is the company name
ProductName is the company
对于您的示例,您可以这样使用
import re
import glob
import ntpath
import os
output_dir = "output"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
old_company_name_pattern = re.compile('ABC Divisionname ProductName|Divisionname ProductName')
for f in glob.glob("*.xml"):
with open(f, 'r', encoding='utf-8') as inputfile:
with open('%s/%s' % (output_dir, ntpath.basename(f)), 'w', encoding='utf-8') as outputfile:
for line in inputfile:
outputfile.write(re.sub(old_company_name_pattern,'ProductName',line))
关于python - 如何在Python脚本中指定要更改的xml文件中的多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718057/