如何使用Python程序将非ascii字符写入文本文件?

时间:2015-12-13 08:00:48

标签: python-3.x text-files non-ascii-characters

# -*- coding: utf-8 -*-
dictionary = {'à': 'a grave', 'â': 'a circumflex', 'ç': 'c cedille', 'é': 'e aigu', 'è': 'e grave', 'ê': 'e circumflex', 'ï': 'i umlet', 'î': 'i cedille', 'ô': 'o circumflex', 'ù': 'u grave', 'û': 'u circumflex'}

location = 'C://Users//Nelson//Desktop//Python//0_Projects//0_Personal//MasterFrenchDictionary//'
#name = raw_input('File Name: ')
name = 'test'

dict_str = str(dictionary)
dict_str = dict_str.replace('{', '')
dict_str = dict_str.replace('}', '')
dict_str = dict_str.replace(', ', '\n')
dict_str = dict_str.replace('l\'', '*')
dict_str = dict_str.replace('d\'', '*')
dict_str = dict_str.replace('"', "'")
dict_str = dict_str.replace("'", '')
dict_str = dict_str.replace('*', "l'")

file = open(location + name + '.txt', 'w')
file.write(dict_str)
file.close()

这是我用来帮助我调试我正在构建的程序的代码。该程序可以访问一个文本文件,其中包含我在法语课程中学到的每个法语单词及其定义。在我的这个迷你调试程序中,字典将被视为字符串,然后删除语法字符。文本文件中的第一行是一个单词:它的定义,第二行是一个单词:它的定义......你明白了。在法语中,有各种重音字符不被ascii识别,我相信你知道。当程序写下这些字符时,我得到this(重音字符:字母和重音名称)。

我尝试使用编解码器模块来解决问题: 我替换了代码:

file = open(location + name + '.txt', 'w')
file.write(dict_str)
file.close()

使用:

with codecs.open(location + name + '.txt', 'w', encoding='utf-8') as out:  
    out.write(u'%s' % dict_str)

但这创建了new problems

如何使用Python程序将非ascii字符写入文本文件?

非常感谢任何帮助!提前谢谢!

1 个答案:

答案 0 :(得分:0)

编辑问题

使用Python 3.4运行代码,我得到了这个文件内容:

ê: e circumflex
à: a grave
ç: c cedille
è: e grave
é: e aigu
û: u circumflex
ï: i umlet
â: a circumflex
ù: u grave
î: i cedille
ô: o circumflex

您使用什么编辑器打开结果文件?如果在Windows上,请使用Notepad++。如果它仍然显示奇怪的内容,请尝试手动更改编辑器中的编码。

改进的解决方案

如果没有全部替换,这应该产生相同的结果:

with open('unicode_out.txt', 'w') as fobj:
    for k, v in dictionary.items():
        fobj.write('{}: {}\n'.format(k, v))
相关问题