我是编程的新手,过去几个月我一直在闲暇时间学习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的内容是:
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.
答案 0 :(得分:8)
您看到的额外空白行是因为您正在使用print
来写出最后已包含换行符的行。由于print
也会编写自己的换行符,因此输出会变为双倍行距。一个简单的解决方法是使用outfile.write(new_line)
代替。
对于文件模式,问题是你一遍又一遍地打开输出文件。你应该在开始时打开它一次。使用with
语句来处理打开的文件通常是个好主意,因为当你完成它们时,它们会为你关闭它们。
我没有看到你的另一个问题,只有一些替代品正在发生。您的词典是否缺少'analyze'
和'utilize'
的拼写?
我提出的一个建议是不要逐行更换。您可以使用file.read()
一次性读取整个文件,然后将其作为一个单元进行处理。这可能会更快,因为它不需要经常循环拼写字典中的项目(只需一次,而不是每行一次):
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))
编辑:
为了让你的代码正确处理包含其他单词的单词(比如“整个”包含“轮胎”),你可能需要放弃简单的str.replace
方法来支持正则表达式。
这是一个快速抛出的解决方案,使用re.sub
,给出了从美国英语到英国英语的拼写更改字典(即,与当前字典的顺序相反):
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()
这个代码结构的一个好处是,如果您将其他顺序的字典传递给replacer_factory
函数,您可以轻松地将英国英语拼写转换回美国英语拼写。
答案 1 :(得分:3)
print
语句添加了自己的换行符,但您的行已经有了自己的换行符。您可以从new_line
中删除换行符,也可以使用较低级别的
output.write(new_line)
代替(将完全写入传递给它的内容)。
对于你的第二个问题,我认为我们需要一个实际的例子。 replace()
确实应该取代所有事件。
>>> "abc abc abcd ab".replace("abc", "def")
'def def defd ab'
我不确定你的第三个问题是什么。如果要替换输出文件,请执行
output = open('output_test_file.txt', 'w')
'w'
表示您正在打开文件进行写作。
答案 2 :(得分:2)
正如上面所有的好答案,我写了一个新版本,我觉得它更加pythonic,希望这会有所帮助:
# 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!"
你也可以看到我之前提出的答案,它包含许多最佳实践建议: Loading large file (25k entries) into dict is slow in Python?
这里有一些关于如何编写python更多python的其他提示:) http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
祝你好运:)