【问题标题】:Python encoding unicode utf-8Python 编码 unicode utf-8
【发布时间】:2018-01-14 01:52:24
【问题描述】:

我正在使用 selenium 在网络公式中插入带有德语变音符号的文本输入。 python 脚本的声明编码是 utf-8。该页面使用 utf-8 编码。当我定义一个这样的字符串时,一切正常:

q = u"Hällö" #type(q) returns unicode
...
textbox.send_keys(q)

但是当我尝试使用 ConfigParser(或其他类型的文件)从配置文件中读取时,我在 webformular (Hällö) 中得到格式错误的输出。这是我使用的代码:

the_encoding = chardet.detect(q)['encoding'] #prints utf-8
q = parser.get('info', 'query') # type(q) returns str
q = q.decode('unicode-escape') # type(q) returns unicode
textbox.send_keys(q)

给 send_keys 函数的两个 q 有什么区别?

【问题讨论】:

  • 改用q.decode('latin-1')。
  • 得到同样的畸形输出
  • 这是 mojibake 的经典例子。如果您在 UTF-8 终端(在 Python 2 或 3 中)执行此操作:print(u"Hällö".encode('utf8').decode('latin1')),您将获得 Hällö。相反,print(u'Hällö'.encode('latin1').decode('utf8')) 打印 Hällö。

标签: python unicode encoding utf-8 character-encoding


【解决方案1】:

这可能是错误的编码。尝试在最后一条语句之前打印q,看看它是否相等。这行q = parser.get('info', 'query') # type(q) returns str 应该返回字符串'H\xc3\xa4ll\xc3\xb6'。如果不同,则说明您使用了错误的编码。

>>> q = u"Hällö"  # unicode obj
>>> q
u'H\xe4ll\xf6'
>>> print q
Hällö
>>> q.encode('utf-8')
'H\xc3\xa4ll\xc3\xb6'
>>> a = q.encode('utf-8')  # str obj
>>> a
'H\xc3\xa4ll\xc3\xb6'  # <-- this should be the value of the str
>>> a.decode('utf-8')  # <-- unicode obj
u'H\xe4ll\xf6'
>>> print a.decode('utf-8')
Hällö
>>> 

【讨论】:

    【解决方案2】:
    from ConfigParser import SafeConfigParser
    import codecs
    
    parser = SafeConfigParser()
    
    with codecs.open('cfg.ini', 'r', encoding='utf-8-sig') as f:
        parser.readfp(f)
    greet = parser.get('main', 'greet')
    
    print 'greet:', greet.encode('utf-8-sig')
    

    问候:哈洛

    cfg.ini 文件

    [main]
    greet=Hällö
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      • 2016-05-03
      • 2018-05-17
      相关资源
      最近更新 更多