python(22)總結下最近遇到的編碼問題

2021-09-08 04:19:00 字數 820 閱讀 2495

最近爬取,或者解析網頁是總是遇到編碼問題(我的版本:python2.7)

一、常見異常:unicodeencodeerror: 'ascii' codec can't encode character u'\xb4' in position 0: ordinal not in range(128)

常見解決方案:在**頭新增如下檔案

import

sysreload(sys)

sys.setdefaultencoding(

"utf-8

")

有時也會遇到字元轉換的問題:

>>> str(u'我'

)traceback (most recent call last):

file

"", line 1, in

unicodeencodeerror:

'ascii

' codec can'

t encode character u

'\u6211'

in position 0: ordinal not in range(128)

解決方法如下:

>>> str(u'

我'.encode('

utf-8'))

'\xe6\x88\x91

'

二、在爬取網頁進行解析的時候,遇到中文需要儲存的,一般要先看一下中文是什麼格式的,如果是unicode則需要進行轉碼

xx = ***.encode('

utf-8')

f.write(xx)

python 2 2蟒蛇例項(turtle函式)

def drawsnake rad,angle,len,neckrad def定義函式 函式是一組 的集合,用於表達乙個功能,或者說函式表達一組 的歸屬,函式名稱是這段 的名字 def所定義的函式在程式中未經呼叫不能直接執行,需要通過函式名呼叫才能夠執行 for i in range len tur...

Python 2 2 函式 變數作用域

通常而言,在程式語言中,變數的作用域從 結構形式來看,有塊級 函式 類 模組 包等由小到大的級別。但是在 python 中,沒有塊級作用域,也就是類似 if 語句塊 for 語句塊 with 上下文管理器等等是不存在作用域概念的,他們等同於普通的語句。if true if語句塊沒有作用域 x 1 p...

python22 正規表示式

1 普通字元作為原子 import re re專門做正則的模組 1 普通字元作為原子 search匹配出來的資料可以看見它的具體位置 re2 re.match a,str1 match從開頭匹配,若從開始就沒有,則為空,只在開頭匹配 re3 re.compile str1 返回本身乙個str1物件,...