<p>您看到的额外空行是因为您正在使用<code>print</code>写出一行,该行的末尾已经包含一个换行符。由于<code>print</code>也编写了自己的换行符,因此您的输出将变为双倍行距。一个简单的解决方法是使用<code>outfile.write(new_line)</code>代替。</p>
<p>至于文件模式,问题是您要反复打开输出文件。你应该一开始就打开一次。使用<code>with</code>语句来处理打开的文件通常是一个好主意,因为当您处理完它们时,它们会帮您关闭它们。</p>
<p>我不理解你的另一个问题,只有一些替代发生。你的字典缺少<code>'analyze'</code>和<code>'utilize'</code>的拼写吗?</p>
<p>我的一个建议是不要逐行更换。您可以使用<code>file.read()</code>一次读取整个文件,然后将其作为单个单元处理。这可能会更快,因为它不需要在拼写词典中的项目上循环那么频繁(只循环一次,而不是每行循环一次):</p>
<pre><code>with open('test_file.txt', 'r') as in_file:
text = in_file.read()
with open('output_test_file.txt', 'w') as out_file:
out_file.write(replace_all(text, spelling_dict))
</code></pre>
<p>编辑:</p>
<p>为了使代码正确地处理包含其他单词的单词(比如包含“tire”的“entire”),您可能需要放弃简单的<code>str.replace</code>方法,转而使用正则表达式。</p>
<p>下面是一个使用<code>re.sub</code>的快速拼凑解决方案,给出了一个从美式英语到英式英语的拼写变化词典(即,与当前词典的顺序相反):</p>
<pre><code>import re
#from english_american_dictionary import ame_to_bre_spellings
ame_to_bre_spellings = {'tire':'tyre', 'color':'colour', 'utilize':'utilise'}
def replacer_factory(spelling_dict):
def replacer(match):
word = match.group()
return spelling_dict.get(word, word)
return replacer
def ame_to_bre(text):
pattern = r'\b\w+\b' # this pattern matches whole words only
replacer = replacer_factory(ame_to_bre_spellings)
return re.sub(pattern, replacer, text)
def main():
#with open('test_file.txt') as in_file:
# text = in_file.read()
text = 'foo color, entire, utilize'
#with open('output_test_file.txt', 'w') as out_file:
# out_file.write(ame_to_bre(text))
print(ame_to_bre(text))
if __name__ == '__main__':
main()
</code></pre>
<p>这种代码结构的一个好处是,如果您按照另一个顺序将字典传递给<code>replacer_factory</code>函数,那么您可以轻松地从英式英语拼写转换回美式英语拼写。</p>