Python提取Excel数据并转换为特定格式的列表字典

本文介绍如何使用Python从Excel文件中提取指定列的数据,并将数据转换成形如 sentences = [ {...}, {...}, {...} ] 的列表字典结构,最后将结果保存到文本文件中。

import pandas as pd
import re

# 读取Excel文件
df = pd.read_excel('C:\Users\86186\Desktop\汽车之家_秦plus_评论.xls')

# 初始化字典列表
sentences = []

# 遍历每一行数据
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['智能化'] = []

        # 添加到字典列表中
        sentences.append(sentence_dict)

# 保存结果到文件
with open('打印结果.txt', 'w', encoding='utf-8') as file:
    file.write('sentences = [
')
    for sentence_dict in sentences:
        file.write('    ' + str(sentence_dict) + ',
')
    file.write(']')

# 打印结果
for sentence_dict in sentences:
    print(sentence_dict)

代码说明:

  1. 使用pandas库读取Excel文件。
  2. 使用循环遍历每一行数据,提取'最满意'、'最不满意'和'智能化'列的内容。
  3. 使用re.split()函数按逗号分句,并将每个句子去除首尾空格后添加到字典中。
  4. 将所有字典添加到列表中,最终得到形如 sentences = [ {...}, {...}, {...} ] 的结构。
  5. 使用with open()将结果保存到文本文件中。

使用说明:

  1. 请确保已安装pandas库:pip install pandas
  2. 将代码中的Excel文件路径修改为你的实际路径。
  3. 运行代码后,结果将保存在代码目录下的'打印结果.txt'文件中。
Python提取Excel数据并转换为特定格式的列表字典

原文地址: http://www.cveoy.top/t/topic/S8I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录