【发布时间】:2014-09-22 09:50:02
【问题描述】:
我是 python 初学者,想学习如何替换不同文件中的文本。
我知道该怎么做,但需要帮助:
我有 3 个文件 main.txt、names.txt 和 number.txt
names.txt 看起来像这样:
Anna
Smith
Bob
Jhon
number.txt 看起来像这样:
1-522-223
1-523-232
1-593-573
1-322-242
filenames.txt 中的第 1 行对应 number.txt 中的第 1 行(所以 anna 的电话是 number.txt 中的第一个,Smith 的电话是 number.txt 中的第二个等等)
现在问题来了: 文件 main.txt 如下所示:
The person Judy lives in Ontario and has phone number 1-888-2923
The person Michael lives in Toronto and has phone number 1-999-2388
The person Cameron lives in Berlin and has phone number 1-666-2888
The person Douglas lives in Tokyo and has phone number 5-7777-223
我知道如何查找和替换,问题是我需要将 main.txt 中每一行的电话和姓名更改为 numbers.txt 和 names 中的相应行。 txt。 所以编辑后的main.txt应该是:
The person Anna lives in Ontario and has phone number 1-522-223
The person Smith lives in Toronto and has phone number 1-523-232
The person Bob lives in Berlin and has phone number 1-593-573
and so on...
我真的不知道该怎么做,而且文件很大,像 2000 行文本。谁能帮帮我?
【问题讨论】:
-
你能把你写的代码贴出来吗?
-
为什么要以三个文件中的信息开头?不同步太容易了,不妨考虑使用 CSV 样式的文件,其中包含不同列中的信息。