我正在尝试是否可以使用Python + Web 界面来获取具有非标准标头的文件,上传它们,并吐出标准化文件。例如。
FN | 闪电网络 |
---|---|
约翰 | 美国能源部 |
简 | 美国能源部 |
FstNm | LstNm |
---|---|
约翰 | 美国能源部 |
简 | 美国能源部 |
名字 | 姓氏 |
---|---|
约翰 | 美国能源部 |
简 | 美国能源部 |
等等等等
我发送的很多文件没有标准标头。有没有一种方法可以将所有 3 个文件导入到 Web 工具中,其中脚本在后台运行以将标头重命名为“First_Name”和“Last_Name”?
我对Python还很陌生,所以到目前为止我所做的只是尝试研究其可行性。
def process_file(file):
# Read the uploaded file into a DataFrame
df = pd.read_excel(file)
# Convert all column headers to lowercase
df.columns = [col.lower() for col in df.columns]
# Search for headers containing "f" or "l" and replace them with "First_Name" and "Last_Name"
new_columns = []
for col in df.columns:
new_col = col
if 'f' in col:
new_col = 'first_name'
if 'l' in col:
new_col = 'last_name'
new_columns.append(new_col)
df.columns = new_columns
# Write the modified DataFrame to an Excel file
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, index=False)
writer.save()
output.seek(0)
return output