python 处理xls表出现多种编码混合的问题

多编码

示例

通过加载数据,使用chardet检查编码,如下:

# -*- coding: utf-8 -*-
import os
import pandas as pd
import numpy as np
import chardet

path = 'D:\\数据.csv'
if os.path.exists(path):
    print('OK')
ac = []
with open(path, 'rb') as f:
    ac.append(f.readlines())
ac
import chardet
ac = np.array(ac)
for i in ac:
    print(i.shape)
    for j in i:
        re = chardet.detect(j)
        print(re)
>>>(4707,)
{'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}
{'encoding': 'ISO-8859-1', 'confidence': 0.73, 'language': ''}
{'encoding': 'ISO-8859-1', 'confidence': 0.73, 'language': ''}

出现这种混合编码的情况

解决办法:使用暴力复制,直接复制表格中的内容,将所有的表格分开复制到.txt文本中,并且使用utf-8的编码方式存储。
然后用pd.read_csv 打开。
再对读取到的内容进行处理。使用\t分离各个数据值,按照原本要求组织dataframe 并按照要求写入csv或者是npy文件中。

你可能感兴趣的:(python,数学建模,开发语言)