我正在制作一个程序,该程序使用带有瑞典字符的单词并将它们存储在列表中。我可以在将它们放入列表之前打印瑞典字符,但是在放入它们之后,它们不会正常显示,只是一大堆字符。
这是我的代码:
# coding=UTF-8
def get_word(lines, eng=0):
if eng == 1: #function to get word in english
word_start = lines[1]
def do_format(word, lang):
if lang == "sv":
first_word = word
second_word = translate(word, lang)
element = first_word + " - " + second_word
elif lang == "en":
first_word = translate(word, lang)
second_word = word
element = first_word + " - " + second_word
return element
def translate(word, lang):
if lang == "sv":
return "ENGLISH"
if lang == "en":
return "SWEDISH"
translated = []
path = "C:\Users\LK\Desktop\Dropbox\Dokumentai\School\Swedish\V47.txt"
doc = open(path, 'r') #opens the documen
doc_list = [] #the variable that will contain list of words
for lines in doc.readlines(): #repeat as many times as there are lines
if len(lines) > 1: #ignore empty spaces
lines = lines.rstrip() #don't add "\n" at the end
doc_list.append(lines) #add to the list
for i in doc_list:
print i
for i in doc_list:
if "-" in i:
if i[0] == "-":
element = do_format(i[2:], "en")
translated.append(element)
else:
translated.append(i)
else:
element = do_format(i, "sv")
translated.append(element)
print translated
raw_input()
我可以将问题简化为简单的代码:
# -*- coding: utf-8 -*-
test_string = "ö"
test_list = ["å"]
print test_string, test_list
如果我运行它,我会得到这个
ö['\ xc3 \ xa5']
答案 0 :(得分:1)
有很多事情需要注意:
u"ö"
代替"ö"
)。并在linux上检查您的语言环境设置(locale
命令)print e
中将打印出str(e)
。对于列表(例如["å"]
),__str__
的实现与__repr__
相同。由于repr(some_list)
会在列表中包含的任何元素上调用repr
,因此您最终会得到您看到的字符串。 repr(string)
的示例:
>>> print u"ö"
ö
>>> print repr(u"ö")
u'\xf6'
>>> print repr("ö")
'\xc3\xb6'
答案 1 :(得分:1)
如果您打印列表,则可以将其打印为某种结构。您应该使用join()
字符串方法将其转换为字符串。使用您的测试代码,它可能看起来像:
print test_string, test_list
print('%s, %s, %s' % (test_string, test_list[0], ','.join(test_list)))
输出:
ö ['\xc3\xa5']
ö, å, å
我认为在你的主程序中你可以:
print('%s' % (', '.join(translated)))
答案 2 :(得分:0)
您可以使用codecs
模块指定读取字节的编码。
import codecs
doc = codecs.open(path, 'r', encoding='utf-8') #opens the document
使用codecs.open
打开的文件将在使用指定编码解码原始字节后为您提供unicode字符串。
在你的代码中,在字符串文字前加上u
,以使它们成为unicode字符串。
# -*- coding: utf-8 -*-
test_string = u"ö"
test_list = [u"å"]
print test_string, test_list[0]