【发布时间】:2015-12-13 08:00:47
【问题描述】:
# -*- 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 字符写入文本文件?
非常感谢任何帮助!提前谢谢!
【问题讨论】:
-
您是否尝试过将
encoding='utf-8'作为关键字参数传递给您的open调用? -
您的文件看起来包含您想要的字符,编码为 utf-8。在支持 utf-8 的文本编辑器中打开文件,看看它长什么样。
标签: python-3.x text-files non-ascii-characters