3.11

import pandas as pd
from sqlalchemy import create_engine
import os
import chardet # 用于检测文件编码

# 定义标准字段映射(根据实际需求修改)
standard_columns = {
'姓名': ['姓名', '名字', 'Name', 'username'],
'年龄': ['年龄', 'Age', '年纪'],
'ID': ['ID', '用户ID', '编号', 'UID','序号'],
'邮箱': ['邮箱', 'Email', 'email地址'],
'技术领域':['技术领域','行业','应用行业名称','成果类别'],
'单位名称':['单位名称','完成单位','单位','成果产出单位'],
'年度':['年度','成果分布年份']
}

# 创建字段映射字典(处理大小写和空格)
column_mapping = {}
for std_col, aliases in standard_columns.items():
for alias in aliases:
normalized_alias = alias.strip().lower().replace(' ', '')
column_mapping[normalized_alias] = std_col


def process_column_name(col_name):
"""处理列名:去除空格、转小写后匹配映射"""
processed = col_name.strip().lower().replace(' ', '')
return column_mapping.get(processed, col_name.strip())


# 读取并处理文件
def process_files(folder_path):
dfs = []
common_encodings = ['utf-8', 'gbk', 'ISO-8859-1', 'latin1'] # 常见编码列表

for file in os.listdir(folder_path):
file_path = os.path.join(folder_path, file)

# 尝试读取CSV文件
if file.endswith('.csv'):
df = None
for encoding in common_encodings:
try:
df = pd.read_csv(
file_path,
encoding=encoding,
on_bad_lines='skip'
)
print(f"成功读取文件 {file},编码:{encoding}")
break
except Exception as e:
print(f"读取文件 {file_path} 时出错:{str(e)}")
continue

# 尝试读取Excel文件
elif file.endswith('.xlsx'):
try:
df = pd.read_excel(file_path)
print(f"成功读取文件 {file},格式:Excel")
except Exception as e:
print(f"读取文件 {file_path} 时出错:{str(e)}")
df = None

# 如果读取成功,处理并添加到列表
if df is not None:
# 处理列名
df.rename(columns=process_column_name, inplace=True)

# 确保列名唯一
df.columns = [f"{col}_{i}" if list(df.columns).count(col) > 1 else col
for i, col in enumerate(df.columns)]

# 添加到列表
dfs.append(df)

# 合并所有DataFrame
if dfs:
combined_df = pd.concat(dfs, axis=0, ignore_index=True, sort=False)
return combined_df
else:
return pd.DataFrame()


# 数据库配置(根据实际情况修改)
DB_CONFIG = {
'user': 'root',
'password': '14734504',
'host': 'localhost',
'port': '3306',
'database': 'shujuqingxi',
'table_name': 'total3'
}


def save_to_mysql(df):
"""保存数据到MySQL"""
if not df.empty:
# 创建数据库连接
engine = create_engine(
f"mysql+pymysql://{DB_CONFIG['user']}:{DB_CONFIG['password']}@"
f"{DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}"
)

# 保存数据
df.to_sql(
name=DB_CONFIG['table_name'],
con=engine,
index=False,
if_exists='replace', # 可根据需求改为'append'
chunksize=500
)
print(f"数据成功保存到MySQL表 {DB_CONFIG['table_name']}")
else:
print("没有数据需要保存")


if __name__ == "__main__":
# 文件夹路径(修改为实际路径)
folder_path = 'E:/pythonprojects/shujuqingxi/.venv/csv'

# 处理并合并数据
combined_data = process_files(folder_path)

# 显示合并后的列信息
if not combined_data.empty:
print("合并后的字段列表:", combined_data.columns.tolist())
print("总记录数:", len(combined_data))

# 保存到MySQL
save_to_mysql(combined_data)
else:
print("未找到文件或数据为空")

posted @ 2025-03-11 22:16  混沌武士丞  阅读(7)  评论(0)    收藏  举报