Python 2.7 - 使用字典从文本文件中查找并替换为新的文本文件

Dar*_*nes 5 python python-2.7

我是编程的新手,过去几个月我一直在闲暇时间学习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()
Run Code Online (Sandbox Code Playgroud)

我确信有一个更好的方法可以解决问题,但对于这个脚本,这里是我遇到的问题:

  • 在输出文件中,每行都写入行,并在它们之间有换行符,但原始的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.
Run Code Online (Sandbox Code Playgroud)

Blc*_*ght 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))
Run Code Online (Sandbox Code Playgroud)

编辑:

为了使你的代码正确处理包含其他单词的单词(比如"整个"包含"轮胎"),你可能需要放弃简单的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()
Run Code Online (Sandbox Code Playgroud)

这个代码结构的一个好处是你可以轻松地将英国英语拼写转换回美国英语拼写,如果你将其他顺序的字典传递给replacer_factory函数.