Python编码Unicode UTF-8 [英] Python encoding unicode utf-8

查看:140
本文介绍了Python编码Unicode UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using selenium to insert text input with german umlauts in a web formular. The declared coding for the python script is utf-8. The page uses utf-8 encoding. When i definine a string like that everything works fine:

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

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

But when i try to read from a config file using ConfigParser (or another kind of file) i get malformed output in the webformular (Hällö). This is the code i use for that:

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之间有什么区别? / p>

Whats the difference between the both q's given to the send_keys function?

推荐答案

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')

问候:Hällö

cfg.ini文件

[main]
greet=Hällö

这篇关于Python编码Unicode UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆