You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
98 lines
3.4 KiB
98 lines
3.4 KiB
import os
|
|
import pandas as pd
|
|
|
|
# 输入输出文件路径
|
|
input_file = r'D:\计量经济学\计量实验资料及作业要求\计量实验资料及作业要求\图文帖子原始信息计量实验使用.xlsx'
|
|
output_file = r'D:\计量经济学\计量实验资料及作业要求\计量实验资料及作业要求\图文帖子实验数据(新).csv'
|
|
|
|
print("========================================")
|
|
print(" Python 数据清洗脚本 v2")
|
|
print("========================================")
|
|
print(f"输入文件: {input_file}")
|
|
print(f"输出文件: {output_file}")
|
|
print()
|
|
|
|
# 检查文件是否存在
|
|
if not os.path.exists(input_file):
|
|
print("错误: 输入文件不存在!")
|
|
print(f"检查路径: {input_file}")
|
|
exit(1)
|
|
|
|
print(f"文件大小: {os.path.getsize(input_file) / 1024:.2f} KB")
|
|
print(f"文件存在: {os.path.exists(input_file)}")
|
|
|
|
# 读取Excel文件
|
|
try:
|
|
print("正在读取Excel文件...")
|
|
# 尝试读取前10行数据
|
|
df = pd.read_excel(input_file, nrows=10)
|
|
print(f"成功读取 {len(df)} 行示例数据")
|
|
print(f"列名: {list(df.columns)}")
|
|
|
|
# 读取全部数据
|
|
print("正在读取全部数据...")
|
|
df = pd.read_excel(input_file)
|
|
print(f"成功读取 {len(df)} 行完整数据")
|
|
|
|
# 数据清洗
|
|
print("正在清洗数据...")
|
|
|
|
# 1. 处理缺失值
|
|
print(f"清洗前 - 缺失值统计:")
|
|
print(df.isnull().sum())
|
|
df = df.fillna('')
|
|
|
|
# 2. 去除文本中的多余空格
|
|
for col in df.columns:
|
|
if df[col].dtype == 'object':
|
|
df[col] = df[col].astype(str).str.strip()
|
|
df[col] = df[col].str.replace('\\s+', ' ', regex=True)
|
|
|
|
# 3. 规范化情感倾向
|
|
if '情感倾向' in df.columns:
|
|
def normalize_sentiment(sentiment):
|
|
if pd.isna(sentiment) or sentiment == '':
|
|
return '中性'
|
|
sentiment = str(sentiment).lower()
|
|
if any(keyword in sentiment for keyword in ['积极', '正面', 'positive']):
|
|
return '积极'
|
|
elif any(keyword in sentiment for keyword in ['消极', '负面', 'negative']):
|
|
return '消极'
|
|
else:
|
|
return '中性'
|
|
|
|
df['情感倾向'] = df['情感倾向'].apply(normalize_sentiment)
|
|
print("情感倾向规范化完成")
|
|
|
|
# 4. 确保输出目录存在
|
|
output_dir = os.path.dirname(output_file)
|
|
print(f"输出目录: {output_dir}")
|
|
print(f"目录存在: {os.path.exists(output_dir)}")
|
|
|
|
if not os.path.exists(output_dir):
|
|
print("正在创建输出目录...")
|
|
os.makedirs(output_dir)
|
|
|
|
# 保存为CSV文件
|
|
print("正在保存清洗后的数据...")
|
|
print(f"保存路径: {output_file}")
|
|
|
|
df.to_csv(output_file, index=False, encoding='utf-8-sig')
|
|
|
|
# 验证文件是否创建成功
|
|
if os.path.exists(output_file):
|
|
print(f"数据已成功保存到: {output_file}")
|
|
print(f"保存文件大小: {os.path.getsize(output_file) / 1024:.2f} KB")
|
|
print(f"保存了 {len(df)} 行清洗后的数据")
|
|
else:
|
|
print("错误: 文件保存失败,未找到输出文件")
|
|
|
|
print()
|
|
print("========================================")
|
|
print(" 数据清洗任务完成")
|
|
print("========================================")
|
|
|
|
except Exception as e:
|
|
print(f"处理文件时出错: {str(e)}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
|