擅长:python、mysql、java
<p>作为以上所有的好答案,我写了一个新版本,我认为是更Python,希望这有助于:</p>
<pre><code># imported dictionary contains 1800 english:american spelling key:value pairs.
mydict = {
'color': 'colour',
}
def replace_all(text, mydict):
for english, american in mydict.iteritems():
text = text.replace(american, english)
return text
try:
with open('new_output.txt', 'w') as new_file:
with open('test_file.txt', 'r') as f:
for line in f:
new_line = replace_all(line, mydict)
new_file.write(new_line)
except:
print "Can't open file!"
</code></pre>
<p>你也可以看到我之前问的答案,它包含许多最佳实践建议:
<a href="https://stackoverflow.com/questions/10168349/loading-large-file-25k-entries-into-dict-is-slow-in-python">Loading large file (25k entries) into dict is slow in Python?</a></p>
<p>下面是一些关于如何编写更多python的其他技巧:)
<a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html" rel="nofollow noreferrer">http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html</a></p>
<p>祝你好运:)</p>