日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python3里gbk編碼的問題解決_python

作者:哈哈的獅子 ? 更新時間: 2022-10-16 編程語言

在python3有關字符串的處理當中,經常會遇到

'gbk' codec can't encode character '\xa0'這個問題,原因是在str里面存在著不能正確編碼的字符。

通過以下方法即可解決。

import requests
from bs4 import BeautifulSoup
url = "http://jecvay.com/2015/03/learning-compilers-1.html"
url = url.encode('gbk','ignore').decode('utf-8') //忽略
response = requests.get(url)
print(response)
soup = BeautifulSoup(response.text)

print(soup.body.text)

以上方法在必須要記錄數據的時候會出現數據不準確問題

python3 字符串無法將 gbk 完全轉換為utf8

對于必須存儲的情況,將gbk -> 十六進制字節碼文本 保存,需要的時候在轉換為gbk以便顯示。

def string_hex(data):
    lin = ['%02X' % i for i in data]
    return "".join(lin).upper()
 
 
def __ToUTF8(tuple):
    lists = []
    for itme in tuple:
        tmp = itme
        if type(itme) == bytes:
            try:
                tmp = itme.decode('gbk')
            except UnicodeDecodeError:
                tmp = string_hex(itme)
        lists.append(tmp)
    return lists
def readFileAll(file):
    with open(file, 'rb') as f:
        data = f.read()
    return data
s = readFileAll('gkb.txt') //gbk 字符串文件
sx = string_hex(s)//轉化為16進制文本
print(sx)

原文鏈接:https://wozd1.blog.csdn.net/article/details/80920290

欄目分類
最近更新