簡體   English   中英

Python編碼Unicode UTF-8

[英]Python encoding unicode utf-8

我正在使用硒在Web公式中插入帶有德國變音符號的文本輸入。 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 ,看是否相等。 這行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ö
>>> 
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ö

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM