【问题标题】:How do I write non-ascii characters to a text file using a Python program?如何使用 Python 程序将非 ascii 字符写入文本文件?
【发布时间】: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


【解决方案1】:

编辑器问题

用 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))

【讨论】:

  • 我目前正在使用 Enthought Canopy。我已经安装了 Notepad++,但我还没有使用它。感谢您提供改进的解决方案。我没有安装 python,因为 Canopy 会处理它,但我会下载它并尝试使用记事本。感谢您的帮助!
  • @Nelson 应该只需要一两秒钟。只需打开 Notepad++ 并转到菜单 File-->Open 并打开您生成的文件。
猜你喜欢
  • 2014-04-04
  • 2016-01-20
  • 2014-04-05
  • 1970-01-01
  • 2013-05-13
  • 2019-05-18
  • 2010-10-12
  • 1970-01-01
相关资源
最近更新 更多