擅长:python、mysql、java
<p>这里有两件事:</p>
<p>不建议使用replace,有关详细信息,请参阅此讨论:
<a href="https://stackoverflow.com/questions/8267219/python-2-7-replace-method-of-string-object-deprecated">Python 2.7: replace method of string object deprecated</a></p>
<p>如果您担心一次将data.txt读入内存,那么您应该能够一次在data.txt上迭代一行</p>
<pre><code>data = open("data.txt", 'r')
for line in data:
# fix the line
</code></pre>
<p>所以剩下的就是一堆查找/替换对并修复每一行。查看<a href="http://docs.python.org/2/library/functions.html#zip" rel="nofollow noreferrer" title="zip">zip</a>函数以获得一种简便的方法</p>
<pre><code>find = open("find.txt", 'r').readlines()
replace = open("replace.txt", 'r').readlines()
new_data = open("new_data.txt", 'w')
for find_token, replace_token in zip(find, replace):
new_line = line.replace(find_token, replace_token)
new_data.write(new_line + os.linesep)
</code></pre>