Python 代码将 Excel 数据整理至列表并写入文件
非常抱歉我之前的误解。以下是修改后的代码,将原本要存入文件的数据包含在一个名为'sentences0209'的列表中:
import pandas as pd
import re
# 读取Excel文件
df = pd.read_excel("C:\Users\86186\Desktop\汽车之家_秦plus_评论.xls")
# 初始化字典列表
sentences0209 = []
# 遍历每一行数据
for index, row in df.iterrows():
if pd.notnull(row['用户昵称']) and pd.notnull(row['最满意']):
sentence_dict = {}
# 提取最满意的内容并按逗号分句
max_satisfaction = str(row['最满意'])
max_satisfaction = re.split(r'[,,]', max_satisfaction)
sentence_dict['最满意'] = [sentence.strip() for sentence in max_satisfaction]
# 提取最不满意的内容并按逗号分句
if pd.notnull(row['最不满意']):
min_satisfaction = str(row['最不满意'])
min_satisfaction = re.split(r'[,,]', min_satisfaction)
sentence_dict['最不满意'] = [sentence.strip() for sentence in min_satisfaction]
else:
sentence_dict['最不满意'] = []
# 提取智能化的内容
if pd.notnull(df.iloc[index+1]['智能化']):
intelligence = str(df.iloc[index+1]['智能化'])
intelligence = re.split(r'[,,]', intelligence)
sentence_dict['智能化'] = [sentence.strip() for sentence in intelligence]
else:
sentence_dict['智能化'] = []
# 添加到字典列表中
sentences0209.append(sentence_dict)
# 保存结果到文件
with open("打印结果.txt", "w", encoding="utf-8") as file:
file.write("sentences0209 = " + str(sentences0209))
# 打印结果
for sentence_dict in sentences0209:
print(sentence_dict)
这段代码将原本要存入文件的数据包含在一个名为'sentences0209'的列表中,并将整个'sentences0209'列表以字符串形式写入文件中。请确保你已经安装了 pandas 库和 xlrd 库,并将文件路径修改为你的实际路径。
原文地址: http://www.cveoy.top/t/topic/S7f 著作权归作者所有。请勿转载和采集!