太棒啦!我们接着开始下一项工作吧!我想在 分分钟情感词频统计.xlsx 文件中第四列插入一列数据命名为“情感分类”,从 弹幕情感词统计.xlsx 文件中来检测对应的情感分类(文件第一列为情感词,第二列为词语对应的情感分类),帮我整理出来代码
时间: 2025-08-22 19:56:55 浏览: 4
<think>我们将修改代码,在结果DataFrame中增加一列“情感分类”。这需要从“弹幕情感词统计.xlsx”文件中读取情感词及其对应的情感分类(假设第一列是情感词,第二列是情感分类)。
步骤:
1. 读取“弹幕情感词统计.xlsx”文件,创建一个字典,键为情感词,值为情感分类。
2. 在生成结果列表时,对于每个情感词,从字典中获取其情感分类。如果字典中没有,则标记为未知(例如'未知')。
注意:由于一个情感词可能只出现一次,但我们在结果中会多次出现(不同分钟),所以建立映射字典是高效的。
修改点:
- 在读取情感词列表时,同时读取情感分类列,构建映射字典。
- 在生成结果的循环中,对于每个情感词,从映射字典中获取情感分类。
代码调整如下:</think>下面我将修改代码,为结果文件添加"情感分类"列。这需要从"弹幕情感词统计.xlsx"文件中读取情感词对应的情感分类信息:
```python
import pandas as pd
import numpy as np
from collections import defaultdict
import re
import datetime
def parse_timestamp(ts_str):
"""自动解析三种时间格式并转换为总秒数(浮点数)"""
ts_str = str(ts_str).strip()
# 格式1: "分:秒.毫秒" (如 "01:57.6")
if re.match(r'^\d{1,2}:\d{1,2}\.\d+$', ts_str):
parts = ts_str.split(':')
minutes = int(parts[0])
seconds = float(parts[1])
return minutes * 60 + seconds
# 格式2: "时:分:秒.毫秒" (如 "00:02:01.200000")
elif re.match(r'^\d{1,2}:\d{1,2}:\d{1,2}\.\d+$', ts_str):
parts = ts_str.split(':')
hours = int(parts[0])
minutes = int(parts[1])
seconds = float(parts[2])
return hours * 3600 + minutes * 60 + seconds
# 格式3: "时:分:秒" (如 "00:02:08")
elif re.match(r'^\d{1,2}:\d{1,2}:\d{1,2}$', ts_str):
parts = ts_str.split(':')
hours = int(parts[0])
minutes = int(parts[1])
seconds = int(parts[2])
return hours * 3600 + minutes * 60 + seconds
# 无法识别的格式
return None
# 1. 读取情感词列表及情感分类
emotion_df = pd.read_excel('弹幕情感词统计.xlsx')
# 创建情感词到情感分类的映射字典
emotion_mapping = {}
for _, row in emotion_df.iterrows():
word = str(row.iloc[0]).strip()
if len(row) >= 2: # 确保有第二列
category = str(row.iloc[1]).strip()
else:
category = "未知"
emotion_mapping[word] = category
# 获取情感词集合
emotion_words = set(emotion_mapping.keys())
# 2. 读取弹幕数据并处理
danmaku_df = pd.read_excel('热力图实验.xlsx')
timestamps = danmaku_df.iloc[:, 0].tolist() # 第一列:时间戳
danmaku_list = danmaku_df.iloc[:, 1].tolist() # 第二列:弹幕文本
# 3. 解析时间戳并转换为分钟索引
minute_indices = []
for ts in timestamps:
total_seconds = parse_timestamp(ts)
if total_seconds is not None:
# 计算分钟索引(向下取整)
minute_index = int(total_seconds // 60)
minute_indices.append(minute_index)
else:
minute_indices.append(None)
# 4. 按分钟分组统计
minute_word_counts = defaultdict(lambda: defaultdict(int))
minute_danmaku_counts = defaultdict(int) # 用于统计含情感词的弹幕数
# 遍历每条弹幕
for i, (minute_idx, danmaku) in enumerate(zip(minute_indices, danmaku_list)):
if minute_idx is None:
continue # 跳过无效时间戳
# 清洗并分割词语
words = re.split(r'\s+', str(danmaku).strip())
words = [word.strip() for word in words if word.strip()]
# 检查该弹幕是否包含情感词
has_emotion = False
# 统计出现在情感词列表中的词语
for word in words:
if word in emotion_words:
minute_word_counts[minute_idx][word] += 1
has_emotion = True
# 如果弹幕包含至少一个情感词,计数加1
if has_emotion:
minute_danmaku_counts[minute_idx] += 1
# 5. 转换为DataFrame并整理结果(添加情感分类)
results = []
for minute_idx, word_count in minute_word_counts.items():
# 计算该分钟的总弹幕数
total_danmaku = sum(1 for idx in minute_indices if idx == minute_idx)
# 获取该分钟含情感词的弹幕数
emotion_danmaku_count = minute_danmaku_counts.get(minute_idx, 0)
# 添加该分钟的所有情感词统计
for word, count in word_count.items():
# 获取情感词对应的情感分类
emotion_category = emotion_mapping.get(word, "未知")
results.append({
'分钟索引': minute_idx,
'分钟区间': f"{minute_idx//60:02d}:{minute_idx%60:02d}-{(minute_idx+1)//60:02d}:{(minute_idx+1)%60:02d}",
'情感词': word,
'情感分类': emotion_category, # 新增的情感分类列
'出现次数': count,
'该分钟总弹幕数': total_danmaku,
'该分钟含情感词的弹幕数': emotion_danmaku_count,
'该分钟情感词总数': sum(word_count.values())
})
# 创建结果DataFrame
result_df = pd.DataFrame(results)
# 6. 保存结果到Excel
result_df.to_excel('分分钟情感词频统计.xlsx', index=False)
print(f"共统计到 {len(result_df)} 条分分钟情感词记录")
print(f"新增列:'情感分类' - 从情感词映射文件中获取")
print("统计结果已保存到 '分分钟情感词频统计.xlsx'")
```
### 主要修改点:
1. **情感分类映射字典 `emotion_mapping`**:
```python
# 创建情感词到情感分类的映射字典
emotion_mapping = {}
for _, row in emotion_df.iterrows():
word = str(row.iloc[0]).strip()
if len(row) >= 2: # 确保有第二列
category = str(row.iloc[1]).strip()
else:
category = "未知"
emotion_mapping[word] = category
```
- 从"弹幕情感词统计.xlsx"读取情感词及其分类
- 创建字典:`{情感词: 情感分类}`
- 处理缺失分类的情况,默认为"未知"
2. **结果添加情感分类列**:
```python
for word, count in word_count.items():
# 获取情感词对应的情感分类
emotion_category = emotion_mapping.get(word, "未知")
results.append({
...
'情感分类': emotion_category, # 新增的情感分类列
...
})
```
- 在生成每条记录时,从映射字典获取情感分类
- 如果字典中没有对应词,使用"未知"分类
### 输出文件结构:
| 分钟索引 | 分钟区间 | 情感词 | **情感分类** | 出现次数 | 该分钟总弹幕数 | 该分钟含情感词的弹幕数 | 该分钟情感词总数 |
|----------|-------------|--------|--------------|----------|----------------|------------------------|------------------|
| 1 | 00:01-00:02 | 感动 | **积极** | 5 | 20 | 15 | 32 |
| 1 | 00:01-00:02 | 开心 | **积极** | 8 | 20 | 15 | 32 |
| 1 | 00:01-00:02 | 悲伤 | **消极** | 3 | 20 | 15 | 32 |
| 2 | 00:02-00:03 | 愤怒 | **消极** | 12 | 35 | 25 | 45 |
### 使用场景:
1. **情感分类分析**:可以按情感分类(如积极/消极)统计每分钟的情感分布
2. **情感趋势分析**:观察不同情感分类随时间变化的趋势
3. **情感强度对比**:比较不同情感分类在特定时间段的强度
4. **情感关联分析**:研究不同情感分类之间的关系(如积极和消极是否同时出现)
### 后续分析建议:
```python
# 按情感分类统计每分钟的情感词总数
category_summary = result_df.groupby(['分钟索引', '情感分类'])['出现次数'].sum().unstack(fill_value=0)
# 计算每分钟各类情感占比
category_percentage = category_summary.div(category_summary.sum(axis=1), axis=0)
# 保存分类统计结果
category_summary.to_excel('分分钟情感分类统计.xlsx')
category_percentage.to_excel('分分钟情感分类占比.xlsx')
print("情感分类统计已保存到文件")
```
### 注意事项:
1. 确保"弹幕情感词统计.xlsx"文件包含两列:第一列情感词,第二列情感分类
2. 情感分类可以是任意字符串(如"积极"、"消极"、"中性"或更细的分类)
3. 如果情感词在映射文件中没有对应分类,会被标记为"未知"
4. 同一个情感词在不同行中会有相同的情感分类值
阅读全文