python - python错误中的瑞典语字符

标签 python unicode

我正在制作一个程序,该程序使用带有瑞典字符的单词并将它们存储在列表中。在将瑞典语字符放入列表之前,我可以打印它们,但放入列表后,它们无法正常显示,只是一堆乱七八糟的字符。

这是我的代码:

# 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']

最佳答案

有很多事情需要注意:

  1. splinter 的角色。发生这种情况似乎是因为您的 python 似乎输出 UTF-8 但您的终端似乎配置为某种 ISO-8859-X 模式(因此有两个字符)。我会尝试在 Python 2 中使用正确的 unicode 字符串! (始终使用 u"ö" 而不是 "ö")。并检查您的区域设置(Linux 上的 locale 命令)
  2. 列表中奇怪的字符串。在 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/

相关文章:

python - 使用 Python Flask 检查 cookie

java - 当作为参数传递时,在 Java 中正确表示 ^A (Unicode\u0001)

javascript - 您能帮助我更改正则表达式以包含特定范围的 unicode 字符吗?

vim - 输入带有 8 位十六进制代码的 Unicode 字符

python - Pandas 避免在转换后的数字列中添加双引号并附加逗号

python - SQLAlchemy 模型数据未在 Jinja 循环中呈现

java - 如何在 Java 中将 "i"与土耳其语 i 匹配?

unicode - 在 Clojure 源代码中使用表情符号文字

python - 有效语法的语法错误突出显示 - Python 3.6

python - 加快 Python 中 beta Pert 分布的计算