我正在制作一个程序,该程序使用带有瑞典字符的单词并将它们存储在列表中。在将瑞典语字符放入列表之前,我可以打印它们,但放入列表后,它们无法正常显示,只是一堆乱七八糟的字符。
这是我的代码:
# 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
如果我运行它,我会得到这个
block 引用>ö ['\xc3\xa5']
最佳答案
有很多事情需要注意:
- splinter 的角色。发生这种情况似乎是因为您的 python 似乎输出 UTF-8 但您的终端似乎配置为某种 ISO-8859-X 模式(因此有两个字符)。我会尝试在 Python 2 中使用正确的 unicode 字符串! (始终使用
u"ö"
而不是"ö"
)。并检查您的区域设置(Linux 上的locale
命令) - 列表中奇怪的字符串。在 Python 中,
print e
将打印出str(e)
。对于列表(例如["å"]
),__str__
的实现与__repr__
相同。由于repr(some_list)
将对列表中包含的任何元素调用repr
,因此您最终会得到您看到的字符串。
repr(string)
示例:
>>> print u"ö"
ö
>>> print repr(u"ö")
u'\xf6'
>>> print repr("ö")
'\xc3\xb6'
关于python - python错误中的瑞典语字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13526909/