如何在文件中写俄文字符?

时间:2010-07-07 20:59:44

标签: python windows unicode python-2.x python-unicode

在我尝试输出俄语字符的控制台中它给了我????????????????

谁知道为什么?

我尝试写入文件 - 在这种情况下是相同的情况。

例如

f=open('tets.txt','w')
f.write('some russian text')
f.close

里面的文件是 - ??????????????????????? /

p="some russian text"
print p
?????????????

在其他记事本中,不允许我使用俄语字母保存文件。我这样说:

  

此文件包含字符   如果,Unicode格式将丢失   您将此文件保存为ANSI编码   文本文件。保持Unicode   信息,单击下面的取消和   然后选择一个Unicode选项   来自编码下拉列表。   继续?

如何调整我的系统,所以我不会遇到这个问题。

5 个答案:

答案 0 :(得分:15)

这是一个经过深思熟虑的例子,请阅读评论:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8

from __future__ import with_statement   # Not required in Python 2.6 any more

import codecs

p = u"абвгдежзийкл"  # note the 'u' prefix

print p   # probably won't work on Windows due to a complex issue

with codecs.open("tets.txt", "w", "utf-16") as stream:   # or utf-8
    stream.write(p + u"\n")

# Now you should have a file called "tets.txt" that can be opened with Notepad or any other editor

答案 1 :(得分:7)

尝试使用编解码器打开文件,您需要

import codecs

然后

writefile = codecs.open('write.txt', 'w', 'utf-8')

答案 2 :(得分:2)

如果文件编码包含非ASCII字符,则需要定义文件编码。

http://www.python.org/dev/peps/pep-0263/

答案 3 :(得分:1)

您使用的是哪种控制台?机会是,您的控制台不支持该语言。确保您的控制台支持Unicode(并且您的应用程序正在发送Unicode字符串)。

<强>更新

要解决有关Windows记事本问题的更新问题:点击文件 - &gt;另存为,然后从“编码”下拉列表中选择“Unicode”。

答案 4 :(得分:0)

您是否在控制台中键入或仅在控制台中查看结果? petraszd说,这看起来像pep-0263问题。

print p.decode('your-system-encoding')

应该在控制台中工作(我不知道你用于俄语的编码系统是什么)

如果您使用的是.py文件,则需要在文件顶部放置# -*- coding: UTF-8 -*-(用Rusian编码替换utf-8),我认为不需要.decode如果您的操作系统配置了正确的编码,则在print中。 (至少我不需要它,但我不知道它如何与俄语合作)

相关问题