【发布时间】:2013-09-17 13:01:35
【问题描述】:
我是编程新手,过去几个月一直在业余时间学习python。我决定尝试创建一个小脚本,将美国拼写转换为文本文件中的英语拼写。
在过去的 5 个小时里,我一直在尝试各种事情,但最终想出了一些让我更接近目标的方法,但还没有完全实现!
#imported dictionary contains 1800 english:american spelling key:value pairs.
from english_american_dictionary import dict
def replace_all(text, dict):
for english, american in dict.iteritems():
text = text.replace(american, english)
return text
my_text = open('test_file.txt', 'r')
for line in my_text:
new_line = replace_all(line, dict)
output = open('output_test_file.txt', 'a')
print >> output, new_line
output.close()
我确信有更好的方法来处理事情,但是对于这个脚本,我遇到了以下问题:
- 在输出文件中,每行都写在隔行上,中间有一个换行符,但原始的 test_file.txt 没有这个。本页底部显示的 test_file.txt 的内容
- 只有一行中美式拼写的第一个实例会转换为英语。
- 我并不想以附加模式打开输出文件,但无法在此代码结构中找出“r”。
感谢这个热心的新手的任何帮助!
test_file.txt 的内容是:
I am sample file.
I contain an english spelling: colour.
3 american spellings on 1 line: color, analyze, utilize.
1 american spelling on 1 line: familiarize.
【问题讨论】:
-
请注意:使用
dict作为变量的名称是一个非常糟糕的主意,因为它会隐藏内置字典类型的名称。如果您不小心,这可能会导致您的代码以令人困惑的方式中断。 -
感谢您的提示,这里不会使用 'dict' 作为变量。
标签: python python-2.7