(为了更清楚起见,重新措辞问题。)
假设我有 1000 个文本文件。每个文件都是文本形式,具有固定的字段描述和标题,但数据不同。例如,文件 1:
The Foo Factory Date: 2015-10-02 Order Details ------------------------- Order ID: [ 1 ] Amount: [ 1 ] Order Price: [ 12.34 ] Have a nice day.
和文件 2:
The Foo Factory Date: 2016-01-11 Order Details ------------------------- Order ID: [ 7 ] Amount: [ 17 ] Order Price: [ 543.21 ] Have a nice day.
等等。现在,假设我继续将字段描述翻译成法语;并删除了值。所以现在我有:
L'usine Foo Date: Détails de commande ------------------------- Nm.du Commande: [ ] Montant: [ ] Prix du Commande: [ ] Bonne journée.
我不太会说法语,所以请忽略这里的任何错误。无论如何,所有字段的位置完全相同,但非字段值文本不同。我想将此替换应用于所有文件。我该如何实现?
答案1
您已经生成了格式映射,因此剩下的工作就是正则表达式替换。生成映射更困难,尤其是对于较大、更复杂的文本。我使用Sublime Text为此。但这里的用例和进一步的信息不清楚,如果它很重要,你应该把它带到 softwarerecs.SE。无论如何,我都包含了一个 Python 版本:
# -*- coding: utf-8 -*-
import os
SOURCE_DIRECTORY = ''
DEST_DIRECTORY = ''
replacements = ["L'usine Foo ",
"Détails de commande",
"Nm.du Commande: ",
"Montant: ",
"Prix du Commande: ",
"Bonne journée."]
samples = ["The Foo Factory ",
"Order Details",
"Order ID: ",
"Amount: ",
"Order Price: ",
"Have a nice day."]
for filename in os.listdir(SOURCE_DIRECTORY):
with open(os.path.join(SOURCE_DIRECTORY, filename), 'r') as nctn:
text = nctn.read()
for i, val in enumerate(samples):
text = text.replace(val, replacements[i])
with open(os.path.join(DEST_DIRECTORY, filename), 'w') as nctn:
nctn.write(text)