V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
qazwsxkevin
V2EX  ›  Python

pandas.to_html()默认使用 gbk 编码的问题。。。

  •  
  •   qazwsxkevin · 2019-05-17 18:10:55 +08:00 · 1691 次点击
    这是一个创建于 1803 天前的主题,其中的信息可能已经有所发展或是发生改变。

    从一个 html 文件已经读取表格数据进入到 pd
    我准备把 pd 数据写入到一个 html 文件的时候,报了个错误,遇上了困扰了很多人编码类型的问题,

    error in main!! 'gbk' codec can't decode byte 0x94 in position 256: illegal multibyte sequence
    

    SomeFunc.py 里面的 transformCodec()是网上找的一个例子,好像不能正常工作,我理解是 2.x 版本写的,3.x 不合适?

    import requests  
    import pandas as pd  
    import string  
    import time  
    import datetime  
    import codecs  
      
    import SomeFunc  
      
      
    srcfile = 'C:/Users/Administrator/Desktop/src.html'  
      
      
    if __name__ == '__main__':  
        try:  
            f = codecs.open(srcfile, 'r+', 'utf-8')  
            readStr = f.read()  
            f.close()  
            PageDF = PageDF.append(pd.read_html(readStr)[7], ignore_index=True)  
            PageDF = PageDF.drop(PageDF.tail(1).index) #删除最后一行  
            #PageDF = SomeFunc.transformCodec(PageDF)    
            PageDF.to_html('C:/Users/Administrator/Desktop/pcResult/A.html')  
          except Exception as e:
            print('error in main!!', e)
      
      
    #############################  
    SomeFunc.py                 #  
    #############################  
      
    def transformCodec(re_data):  
        try:  
            re_data = re_data.decode('gbk')  
        except Exception as error:  
            print("error")  
            print('delete illegal string,try again...')  
      
            pos = re.findall(r'decodebytesinposition([\d]+)-([\d]+):illegal', str(error).replace(' ', ''))  
            if len(pos) == 1:  
                re_data = re_data[0:int(pos[0][0])] + re_data[int(pos[0][1]):]  
                re_data = transformCodec(re_data)  
                return re_data  
        return re_data
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1023 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:20 · PVG 03:20 · LAX 12:20 · JFK 15:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.