Python中中文路徑處理問題的研究

2021-06-22 18:24:28 字數 1549 閱讀 4549

a = '你' 為 str 物件

a = u'你' 為 unicode 物件

1. >>> print 'u'  + '你'

>>> u浣

輸出亂碼

2. >>> print 'u'  + u'你'

>>> u你

正常3.

>>> print 'u你'

>>> u浣

輸出亂碼

4.>>> print 'u你' + 'u'

>>> u浣爑

輸出亂碼

5. >>> print u'u你' + 'u'

>>> u你u

正常6.

>>> print u'u你' + '你'

出現錯誤 unicodedecodeerror: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

分析:'你'在記憶體中 為 0xe4,而python預設的編碼方案是ascii,ascii無法識別0xe4

7. >>> print u'u你' + u'你'

>>> u你你

正常8.

>>> print 'u你' + u'你'

出現錯誤 unicodedecodeerror: 'ascii' codec can't decode byte 0xe4 in position 1: ordinal not in range(128)

9.>>> print 'u你'.decode('utf-8') + u'你'

>>> u你你

正常10.

而在處理由系統採集的含有中文的路徑時,使用string.decode('utf-8')就不一定行了,因為簡體中文的windows系統預設編碼為gb2312,正體中文版會採用big5碼

實驗過程如下:

file_from = sys.argv[1] 為由系統採集的包含中文的路徑

file_to = file_from[:file_from.rfind('\\')+1].decode('utf-8')  + u'你_' + file_from[file_from.rfind('\\')+1:].decode('utf-8')

print file_to

將出現錯誤:unicodedecodeerror: 'utf8' codec can't decode byte 0xbb in position 24: invalid start byte

應該使用:decode('gb2312')

file_to = file_from[:file_from.rfind('\\')+1].decode('gb2312')  + u'你_' + file_from[file_from.rfind('\\')+1:].decode('gb2312') 

print file_to 正常

11.而如果file_from是由你自己寫入的包含中文的路徑,如file_from = 『c:\你.txt』

那麼就應該用decode('utf-8')

可以參考上面的第7點和第9點

不足及錯誤之處,請批評指正!!謝謝!!

mysql中文處理問題總結

這幾天一直在做乙個學校的開發專案,遇到了mysql中文處理問題,接下來幾天如果有時間,我會把自己在解決問題的過程中的一些思考和問題解決方案寫下來。現在沒有時間。給自己提個醒。create table tablename id int 10 primaey key engine innodb defa...

下標處理問題

下標處理問題 主要是針對於插入排序演算法寫的程式,其他情況可以借鑑這些思路。數學上或者通常意義上,下標都是從1開始的,但是在多數程式語言裡面陣列下標都是從0開始的,這就很惱火了,簡單乙個下標處理起來卻異常麻煩!請看 例如 1 典型的陣列下標越界問題 假設有個陣列 a 0 a 1 我們要用插入法排序,...

python 字元編碼處理問題總結

一直以來,python中的中文編碼就是乙個大問題,為他他並不能智慧型識別編碼,而實際上其他語言也很難做到。str和unicode物件的轉換,通過encode和decode實現。當我們向網頁提交包含中文的表單資料時,常常會出現亂碼的錯誤,拿我這幾天對駕校網上打卡系統實踐舉例吧。可以看到 姓名 那欄提交...