我正在帮助将旧技术文档从旧公司迁移到新公司。我需要删除像这样的旧公司引用:ABC部门名称产品名称至产品名称。
而且也可以是部门名称产品名称至产品名称。
新名称也有技术文档的旧名称:techdoc到newdocname
我发现有些脚本一次只能执行1个。然后,我发现了一个全局脚本,可以一次执行多个文件更改1。
我发现有些脚本可以一次更改1个xml文件。然后,我发现了一个全局脚本,可以一次执行多个文件更改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部门名称产品名称”吗? “部门名称”,“产品名称”?
您可以使用正则表达式替换方法[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))
输出:
ProductName是公司名称
产品名称是公司
例如,您可以这样使用
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))