脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - 使用Python文本分析:数据读取编码错误问题处理

使用Python文本分析:数据读取编码错误问题处理

2023-11-28 16:26PaperCodeTips Python

在使用python进行文本分析时,很多时候数据来源的环境比较复杂,比如来自爬虫数据,那么就可能包含各种意外的字符。在获取了数据后,在文本分析之前的数据清洗时,最经常碰到的一个问题时,打开数据时的数据编码不对的情

python读取数据编码问题处理

使用Python文本分析:数据读取编码错误问题处理

在使用python进行文本分析时,很多时候数据来源的环境比较复杂,比如来自爬虫数据,那么就可能包含各种意外的字符。在获取了数据后,在文本分析之前的数据清洗时,最经常碰到的一个问题时,打开数据时的数据编码不对的情况。

在实践中,一般会尝试各种不同编码方式来尝试读取数据,比如,我们最常见的utf-8格式等,如果不行的话,那么可以采取自动判断该数据的编码格式,如果还是不行,一个可行的方式是跳过该行数据,继续后续的数据读取。

这个过程其实非常简单:

导入python必要的模块

import concurrent.futures
import pandas as pd
import re
import numpy as np
import os
import chardet
  •  concurrent.futures: 用于创建线程池,实现并行处理数据。
  • pandas: 提供数据处理和分析的功能。
  • re: 正则表达式库,用于文本处理。
  • numpy: 提供数值计算功能。
  • os: 用于处理文件路径和文件名。
  • chardet: 用于检测文件编码。

几个功能函数

clean_cell

def clean_cell(cell):
    try:
        return re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', str(cell))
    except Exception as e:
        print(f"Error in clean_cell: {e}")
        return np.nan

 这个函数用于清理数据单元格,保留中文字符、英文字符和数字,其他字符将被移除。

read_file

def read_file(file_path, encoding):
    _, file_extension = os.path.splitext(file_path)
    if file_extension in ['.csv', '.txt']:
        return pd.read_csv(file_path, encoding=encoding, on_bad_lines='skip')
    elif file_extension == '.xlsx':
        return pd.read_excel(file_path)
    elif file_extension == '.json':
        return pd.read_json(file_path)
    else:
        raise ValueError(f"Unsupported file format: {file_extension}")

根据文件扩展名(如 .csv, .xlsx, .json)来决定使用哪种方法读取文件。

process_dataframe

def process_dataframe(file_path):
    # 定义预设的编码格式列表
    encodings = ['utf-8', 'latin-1', 'ISO-8859-1', 'cp1252', 'gbk', 'ascii']
    
    # 尝试预设的编码格式
    for encoding in encodings:
        try:
            df = pd.read_csv(file_path, encoding=encoding, on_bad_lines='skip')
            break
        except UnicodeDecodeError:
            continue
    else:
        # 如果预设的编码格式都不适用,尝试自动检测编码
        try:
            detected_encoding = chardet.detect(open(file_path, 'rb').read())['encoding']
            df = pd.read_csv(file_path, encoding=detected_encoding, on_bad_lines='skip')
        except Exception as e:
            print(f"无法确定文件编码方式或读取文件失败: {e}")
            return None  # 或者使用其他方式处理这种情况

    # 清洗数据
    with concurrent.futures.ThreadPoolExecutor() as executor:
        for column in df.columns:
            cleaned_column = list(executor.map(clean_cell, df[column]))
            df[column] = cleaned_column

    return df

此函数首先检测文件编码,然后读取文件内容到 DataFrame,最后清洗每一列的数据。

主执行过程

file_path = '/path/to/GSZC_Raw.csv'  # 替换为你自己的数据路径
try:
    cleaned_df = process_dataframe(file_path)
    cleaned_file_path = file_path.replace('.csv', '_cleaned.csv')
    cleaned_df.to_csv(cleaned_file_path, index=False)
except Exception as e:
    print(f"Error in main execution: {e}")

经过以上的过程,一般会解决大部分的数据编码错误问题。如果在实践中尝试了以上方法后还是会报错数据编码错误,那么建议逐行读取数据,但这样通常会很慢,如果数据量不是很大的时候,可以采用这种方式,然后利用计算机多线程,提高处理数据的速度。

如果数据量很大,而出现编码错误的部分很少,那么直接舍弃,可能是更好的选择。

原文地址:https://mp.weixin.qq.com/s?__biz=MzA5NjM1NTY4Mw==&mid=2453899527&idx=1&sn=d9cec29a29deddd7e43d13432ad9f503

延伸 · 阅读

精彩推荐