文章目录
初步切割
读取word
内容:
teacher-full_原文
2024年09月09日 13:35
发言人1 00:00
要干嘛呢?
发言人1 00:24
原谅我,我要。
发言人1 00:43
那位白白山。
发言人1 01:12
只从发言人1开始提取,分别存入excel,
当发言人变化时,必定切割,
如果 发言人没发生变化,但是关键动词发生变化。
也进行切割。
用迭代的思路,建立每个行为类别的关键动词库,当检测到关键行为变化时进行切分,
每切分好一行包括三列,
发言人,时间,内容
存入excel
同时基于文本中提取的动词变化类别做切割以及发言人变化
为了在运行过程中添加进度条,可以使用 tqdm 库。tqdm 是一个非常流行的 Python 库,它能帮助我们直观地展示循环中的进度。
路径设置
查看GPU
迁移模型到GPU
# 检查是否有可用的 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
# 将模型迁移到 GPU(如果有的话)
model.to(device)
bert输出空白debug
import re
from docx import Document
from transformers import BertTokenizer, BertModel
import torch
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
from tqdm import tqdm # 导入 tqdm 库
# 检查是否有可用的 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
# 将模型迁移到 GPU(如果有的话)
model.to(device)
# 定义行为类别与中文动词库
behavior_verb_dict = {
'讲授': ['解释', '说明', '阐述', '讲解', '介绍', '列举', '总结', '分析', '描述', '指出'],
'提问': ['问', '询问', '提问', '追问', '质问', '要求', '让你想', '让你回答'],
'指示': ['指示', '要求', '命令', '安排', '布置', '指引', '让你去做', '请完成'],
'反馈与评价': ['评价', '反馈', '表扬', '批评', '指出错误', '修正', '纠正', '总结', '认可']
}
# 函数:生成句子的BERT嵌入
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=8)
inputs = {k: v.to(device) for k, v in inputs.items()} # 将输入迁移到 GPU
outputs = model(**inputs)
# 取 [CLS] token 的向量,代表整个句子的embedding
embedding = outputs.last_hidden_state[:, 0, :].detach().cpu().numpy() # 将结果从 GPU 返回到 CPU
print(f"生成的嵌入向量:{embedding}")
return embedding
# 函数:计算动词与行为类别动词库的相似度,并返回最佳行为类别及其相似度
def get_most_similar_behavior(verb, behavior_verb_dict, threshold=0.7):
verb_embedding = get_bert_embedding(verb)
max_similarity = 0
best_behavior = '未知行为'
for behavior, verb_list in behavior_verb_dict.items():
for behavior_verb in verb_list:
behavior_verb_embedding = get_bert_embedding(behavior_verb)
similarity = cosine_similarity(verb_embedding, behavior_verb_embedding)[0][0] # 计算余弦相似度
if similarity > max_similarity and similarity > threshold:
max_similarity = similarity
best_behavior = behavior
return best_behavior, max_similarity
# 函数:读取Word文档并过滤开头
def extract_text_from_docx(docx_path):
doc = Document(docx_path)
paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
# 打印提取到的段落,调试用
print("提取到的段落内容:", paragraphs)
# 过滤掉特定开头的段落 "这一段 teacher-full_原文 2024年09月09日"
filtered_paragraphs = []
for para in paragraphs:
if not para.startswith("这一段") and not para.startswith("teacher-full_原文"):
filtered_paragraphs.append(para)
return filtered_paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
# 匹配多个发言人和时间
matches = re.findall(r'(发言人\d+)\s+(\d{2}:\d{2})\s+([^\n]+)', paragraph)
# 打印匹配到的内容,调试用
print(f"当前段落: {paragraph}")
print(f"匹配到的发言人、时间和内容: {matches}")
if matches:
return matches
return []
# 函数:处理文档内容并进行语义分类和切分(同时根据发言人和行为类别进行切分)
def process_paragraphs(paragraphs, behavi
CPU能运行的语义相似度代码
import re
from docx import Document
from transformers import BertTokenizer, BertModel
import torch
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
# 定义行为类别与中文动词库
behavior_verb_dict = {
'讲授': ['解释', '说明', '阐述', '讲解', '介绍', '列举', '总结', '分析', '描述', '指出'],
'提问': ['问', '询问', '提问', '追问', '质问', '要求', '让你想', '让你回答'],
'指示': ['指示', '要求', '命令', '安排', '布置', '指引', '让你去做', '请完成'],
'反馈与评价': ['评价', '反馈', '表扬', '批评', '指出错误', '修正', '纠正', '总结', '认可']
}
# 函数:生成句子的BERT嵌入
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=8)
outputs = model(**inputs)
# 取 [CLS] token 的向量,代表整个句子的embedding
return outputs.last_hidden_state[:, 0, :].detach().numpy()
# 函数:计算动词与行为类别动词库的相似度,并返回最佳行为类别及其相似度
def get_most_similar_behavior(verb, behavior_verb_dict, threshold=0.7):
verb_embedding = get_bert_embedding(verb)
max_similarity = 0
best_behavior = '未知行为'
for behavior, verb_list in behavior_verb_dict.items():
for behavior_verb in verb_list:
behavior_verb_embedding = get_bert_embedding(behavior_verb)
similarity = cosine_similarity(verb_embedding, behavior_verb_embedding)[0][0] # 计算余弦相似度
if similarity > max_similarity and similarity > threshold:
max_similarity = similarity
best_behavior = behavior
return best_behavior, max_similarity
# 函数:读取Word文档
def extract_text_from_docx(docx_path):
doc = Document(docx_path)
paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
return paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
match = re.match(r'(发言人\d+)\s+(\d{2}:\d{2})\s+(.*)', paragraph)
if match:
speaker, time, content = match.groups()
return speaker, time, content
return None, None, paragraph
# 函数:处理文档内容并进行语义分类和切分(同时根据发言人和行为类别进行切分)
def process_paragraphs(paragraphs, behavior_verb_dict):
results = []
current_behavior = None
current_speaker = None
for para in paragraphs:
speaker, time, content = extract_speaker_time_content(para)
# 获取当前段落中动词的行为分类及相似度
behavior, similarity = get_most_similar_behavior(content, behavior_verb_dict)
# 如果发言人或当前行为与上一段不同,则进行切分
if speaker != current_speaker or behavior != current_behavior:
results.append({
'发言人': speaker,
'时间': time,
'内容': content,
'行为类别': behavior,
'语义相似度': similarity
})
current_speaker = speaker # 更新发言人
current_behavior = behavior # 更新行为类别
else:
# 如果发言人和行为相同,合并内容
results[-1]['内容'] += ' ' + content
return results
# 函数:将结果保存到Excel
def save_to_excel(data, excel_path):
df = pd.DataFrame(data)
df.to_excel(excel_path, index=False)
# 主程序
docx_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\数据\teacher-full_原文.docx'
excel_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\切割\发言切分结果.xlsx'
# 读取word文档
paragraphs = extract_text_from_docx(docx_path)
# 处理文档内容,进行语义切分
processed_data = process_paragraphs(paragraphs, behavior_verb_dict)
# 保存结果到excel
save_to_excel(processed_data, excel_path)
print(f"处理完成,结果已保存到: {excel_path}")
GPU能用了但是没有加切分规则的代码
import re
from docx import Document
from transformers import BertTokenizer, BertModel
import torch
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
from tqdm import tqdm # 导入 tqdm 库
# 检查是否有可用的 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
# 将模型迁移到 GPU(如果有的话)
model.to(device)
# 定义行为类别与中文动词库
behavior_verb_dict = {
'讲授': ['解释', '说明', '阐述', '讲解', '介绍', '列举', '总结', '分析', '描述', '指出'],
'提问': ['问', '询问', '提问', '追问', '质问', '要求', '让你想', '让你回答'],
'指示': ['指示', '要求', '命令', '安排', '布置', '指引', '让你去做', '请完成'],
'反馈与评价': ['评价', '反馈', '表扬', '批评', '指出错误', '修正', '纠正', '总结', '认可']
}
# 函数:生成句子的BERT嵌入
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=8)
inputs = {k: v.to(device) for k, v in inputs.items()} # 将输入迁移到 GPU
outputs = model(**inputs)
# 取 [CLS] token 的向量,代表整个句子的embedding
embedding = outputs.last_hidden_state[:, 0, :].detach().cpu().numpy() # 将结果从 GPU 返回到 CPU
return embedding
# 函数:计算动词与行为类别动词库的相似度,并返回最佳行为类别及其相似度
def get_most_similar_behavior(verb, behavior_verb_dict, threshold=0.7):
verb_embedding = get_bert_embedding(verb)
max_similarity = 0
best_behavior = '未知行为'
for behavior, verb_list in behavior_verb_dict.items():
for behavior_verb in verb_list:
behavior_verb_embedding = get_bert_embedding(behavior_verb)
similarity = cosine_similarity(verb_embedding, behavior_verb_embedding)[0][0] # 计算余弦相似度
if similarity > max_similarity and similarity > threshold:
max_similarity = similarity
best_behavior = behavior
return best_behavior, max_similarity
# 函数:读取Word文档并过滤开头
def extract_text_from_docx(docx_path):
doc = Document(docx_path)
paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
# 打印提取到的段落,调试用
print("提取到的段落内容:", paragraphs)
# 过滤掉特定开头的段落 "这一段 teacher-full_原文 2024年09月09日"
filtered_paragraphs = []
for para in paragraphs:
if not para.startswith("这一段") and not para.startswith("teacher-full_原文"):
filtered_paragraphs.append(para)
return filtered_paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
# 改进的正则表达式,适应你的文档格式,匹配发言人和任意时间格式
match = re.match(r'(发言人\d+)\s+(\d{1,2}:\d{2})', paragraph)
return match
# 函数:处理文档内容并进行语义分类和切分(同时根据发言人和行为类别进行切分)
def process_paragraphs(paragraphs, behavior_verb_dict):
results = []
current_speaker = None
current_time = None
current_content = ""
# 使用 tqdm 显示进度条
for para in tqdm(paragraphs, desc="Processing paragraphs", unit="段"):
# 提取每个发言人、时间、内容
match = extract_speaker_time_content(para)
if match:
# 如果有匹配,保存之前的内容
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
# 更新当前发言人和时间,并清空内容
current_speaker, current_time = match.groups()
current_content = ""
else:
# 如果没有匹配到发言人和时间,认为这是内容的继续
current_content += " " + para.strip()
# 保存最后一段发言
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
return results
# 函数:将结果保存到Excel
def save_to_excel(data, excel_path):
df = pd.DataFrame(data)
df.to_excel(excel_path, index=False)
# 主程序
docx_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\数据\teacher-full_原文.docx'
excel_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\切割\发言切分结果.xlsx'
# 读取word文档并过滤开头部分
paragraphs = extract_text_from_docx(docx_path)
# 处理文档内容,进行语义切分
processed_data = process_paragraphs(paragraphs, behavior_verb_dict)
# 打印处理后的数据,调试用
print("处理后的数据:", processed_data)
# 保存结果到excel
save_to_excel(processed_data, excel_path)
print(f"处理完成,结果已保存到: {excel_path}")
根据动词变化切分
当发言人变化时,进行切分。
当发言人没有变化,但动词库包含的语义发生变化时,进行切分。
把发言人替换老师和学生的代码
import re
from docx import Document
from transformers import BertTokenizer, BertModel
import torch
from sklearn.metrics.pairwise import cosine_similarity
import pandas as pd
from tqdm import tqdm # 导入 tqdm 库
from collections import Counter # 用于统计发言人发言次数
# 检查是否有可用的 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
# 将模型迁移到 GPU(如果有的话)
model.to(device)
# 定义行为类别与中文动词库
behavior_verb_dict = {
'讲授': ['解释', '说明', '阐述', '讲解', '介绍', '列举', '总结', '分析', '描述', '指出'],
'提问': ['问', '询问', '提问', '追问', '质问', '要求', '让你想', '让你回答'],
'指示': ['指示', '要求', '命令', '安排', '布置', '指引', '让你去做', '请完成'],
'反馈与评价': ['评价', '反馈', '表扬', '批评', '指出错误', '修正', '纠正', '总结', '认可']
}
# 函数:生成句子的BERT嵌入
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=8)
inputs = {k: v.to(device) for k, v in inputs.items()} # 将输入迁移到 GPU
outputs = model(**inputs)
# 取 [CLS] token 的向量,代表整个句子的embedding
embedding = outputs.last_hidden_state[:, 0, :].detach().cpu().numpy() # 将结果从 GPU 返回到 CPU
return embedding
# 函数:计算动词与行为类别动词库的相似度,并返回最佳行为类别及其相似度
def get_most_similar_behavior(verb, behavior_verb_dict, threshold=0.7):
verb_embedding = get_bert_embedding(verb)
max_similarity = 0
best_behavior = '未知行为'
for behavior, verb_list in behavior_verb_dict.items():
for behavior_verb in verb_list:
behavior_verb_embedding = get_bert_embedding(behavior_verb)
similarity = cosine_similarity(verb_embedding, behavior_verb_embedding)[0][0] # 计算余弦相似度
if similarity > max_similarity and similarity > threshold:
max_similarity = similarity
best_behavior = behavior
return best_behavior, max_similarity
# 函数:读取Word文档并过滤开头
def extract_text_from_docx(docx_path):
doc = Document(docx_path)
paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
# 打印提取到的段落,调试用
print("提取到的段落内容:", paragraphs)
# 过滤掉特定开头的段落 "这一段 teacher-full_原文 2024年09月09日"
filtered_paragraphs = []
for para in paragraphs:
if not para.startswith("这一段") and not para.startswith("teacher-full_原文"):
filtered_paragraphs.append(para)
return filtered_paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
# 改进的正则表达式,适应你的文档格式,匹配发言人和任意时间格式
match = re.match(r'(发言人\d+)\s+(\d{1,2}:\d{2})', paragraph)
return match
# 函数:处理文档内容并进行语义分类和切分(根据发言人和动词变化进行切分)
def process_paragraphs(paragraphs, behavior_verb_dict):
results = []
current_speaker = None
current_time = None
current_content = ""
current_behavior = None
speaker_counter = Counter() # 统计发言人发言次数
# 使用 tqdm 显示进度条
for para in tqdm(paragraphs, desc="Processing paragraphs", unit="段"):
# 提取每个发言人、时间、内容
match = extract_speaker_time_content(para)
if match:
# 如果匹配到新的发言人,切分当前发言
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
# 更新当前发言人和时间,并清空内容
current_speaker, current_time = match.groups()
current_content = ""
current_behavior = None
# 统计发言人发言次数
speaker_counter[current_speaker] += 1
else:
# 如果没有发言人和时间,累积当前内容
current_content += " " + para.strip()
# 获取当前内容的行为类别
new_behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
# 如果动词(行为类别)发生变化,切分
if current_behavior and new_behavior != current_behavior:
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': current_behavior,
'语义相似度': similarity
})
# 更新当前行为类别
current_content = ""
# 更新当前的行为类别
current_behavior = new_behavior
# 保存最后一段发言
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
return results, speaker_counter
# 函数:替换发言人名称,将发言最多的替换为“老师”,其余替换为“学生1”、“学生2”依次类推
def replace_speaker_names(results, speaker_counter):
# 找到发言最多的发言人
most_common_speaker, _ = speaker_counter.most_common(1)[0]
speaker_mapping = {}
student_count = 1
for speaker in speaker_counter.keys():
if speaker == most_common_speaker:
speaker_mapping[speaker] = "老师"
else:
speaker_mapping[speaker] = f"学生{student_count}"
student_count += 1
# 替换发言人名称
for result in results:
result['发言人'] = speaker_mapping[result['发言人']]
return results
# 函数:将结果保存到Excel
def save_to_excel(data, excel_path):
df = pd.DataFrame(data)
df.to_excel(excel_path, index=False)
# 主程序
docx_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\数据\teacher-full_原文.docx'
excel_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\切割\发言切分结果.xlsx'
# 读取word文档并过滤开头部分
paragraphs = extract_text_from_docx(docx_path)
# 处理文档内容,进行语义切分
processed_data, speaker_counter = process_paragraphs(paragraphs, behavior_verb_dict)
# 替换发言人名称
processed_data = replace_speaker_names(processed_data, speaker_counter)
# 打印处理后的数据,调试用
print("处理后的数据:", processed_data)
# 保存结果到excel
save_to_excel(processed_data, excel_path)
print(f"处理完成,结果已保存到: {excel_path}")
读取txt的代码
import re
import torch
import pandas as pd
from collections import Counter # 用于统计发言人发言次数
from transformers import BertTokenizer, BertModel
from sklearn.metrics.pairwise import cosine_similarity
from tqdm import tqdm # 导入 tqdm 库
# 检查是否有可用的 GPU
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
device = torch.device('cpu')
model.to(device)
# 定义行为类别与中文动词库
behavior_verb_dict = {
'讲授': ['解释', '说明', '阐述', '讲解', '介绍', '列举', '总结', '分析', '描述', '指出'],
'提问': ['问', '询问', '提问', '追问', '质问', '要求', '让你想', '让你回答'],
'指示': ['指示', '要求', '命令', '安排', '布置', '指引', '让你去做', '请完成'],
'反馈与评价': ['评价', '反馈', '表扬', '批评', '指出错误', '修正', '纠正', '总结', '认可']
}
# 函数:生成句子的BERT嵌入
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=8)
inputs = {k: v.to(device) for k, v in inputs.items()} # 将输入迁移到 GPU
outputs = model(**inputs)
embedding = outputs.last_hidden_state[:, 0, :].detach().cpu().numpy() # 将结果从 GPU 返回到 CPU
return embedding
# 函数:计算动词与行为类别动词库的相似度,并返回最佳行为类别及其相似度
def get_most_similar_behavior(verb, behavior_verb_dict, threshold=0.7):
verb_embedding = get_bert_embedding(verb)
max_similarity = 0
best_behavior = '未知行为'
for behavior, verb_list in behavior_verb_dict.items():
for behavior_verb in verb_list:
behavior_verb_embedding = get_bert_embedding(behavior_verb)
similarity = cosine_similarity(verb_embedding, behavior_verb_embedding)[0][0] # 计算余弦相似度
if similarity > max_similarity and similarity > threshold:
max_similarity = similarity
best_behavior = behavior
return best_behavior, max_similarity
# 函数:读取TXT文件并过滤开头
def extract_text_from_txt(txt_path):
with open(txt_path, 'r', encoding='utf-8') as file:
paragraphs = [line.strip() for line in file if line.strip()]
# 打印提取到的段落,调试用
print("提取到的段落内容:", paragraphs)
# 过滤掉特定开头的段落 "2024年5月7日 下午 6:33|46分钟 12秒"
filtered_paragraphs = []
start_flag = False
for para in paragraphs:
if para.startswith("说话人"): # 从检测到“说话人”开始处理
start_flag = True
if start_flag:
filtered_paragraphs.append(para)
return filtered_paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
# 改进的正则表达式,适应你的文档格式,匹配发言人和任意时间格式
match = re.match(r'(说话人\s*\d+)\s+(\d{1,2}:\d{2})', paragraph)
return match
# 函数:处理文档内容并进行语义分类和切分(根据发言人和动词变化进行切分)
def process_paragraphs(paragraphs, behavior_verb_dict):
results = []
current_speaker = None
current_time = None
current_content = ""
current_behavior = None
speaker_counter = Counter() # 统计发言人发言次数
# 使用 tqdm 显示进度条
for para in tqdm(paragraphs, desc="Processing paragraphs", unit="段"):
# 提取每个发言人、时间、内容
match = extract_speaker_time_content(para)
if match:
# 如果匹配到新的发言人,切分当前发言
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
# 更新当前发言人和时间,并清空内容
current_speaker, current_time = match.groups()
current_content = ""
current_behavior = None
# 统计发言人发言次数
speaker_counter[current_speaker] += 1
else:
# 如果没有发言人和时间,累积当前内容
current_content += " " + para.strip()
# 获取当前内容的行为类别
new_behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
# 如果动词(行为类别)发生变化,切分
if current_behavior and new_behavior != current_behavior:
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': current_behavior,
'语义相似度': similarity
})
# 更新当前行为类别
current_content = ""
# 更新当前的行为类别
current_behavior = new_behavior
# 保存最后一段发言
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
return results, speaker_counter
# 函数:替换发言人名称,将发言最多的替换为“老师”,其余替换为“学生1”、“学生2”依次类推
def replace_speaker_names(results, speaker_counter):
# 找到发言最多的发言人
most_common_speaker, _ = speaker_counter.most_common(1)[0]
speaker_mapping = {}
student_count = 1
for speaker in speaker_counter.keys():
if speaker == most_common_speaker:
speaker_mapping[speaker] = "老师"
else:
speaker_mapping[speaker] = f"学生{student_count}"
student_count += 1
# 替换发言人名称
for result in results:
result['发言人'] = speaker_mapping[result['发言人']]
return results
# 函数:将结果保存到Excel
def save_to_excel(data, excel_path):
df = pd.DataFrame(data)
df.to_excel(excel_path, index=False)
# 主程序
txt_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\数据\teacher-full.txt'
excel_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\切割\第二节发言切分结果.xlsx'
# 读取txt文档并过滤开头部分
paragraphs = extract_text_from_txt(txt_path)
# 处理文档内容,进行语义切分
processed_data, speaker_counter = process_paragraphs(paragraphs, behavior_verb_dict)
# 替换发言人名称
processed_data = replace_speaker_names(processed_data, speaker_counter)
# 打印处理后的数据,调试用
print("处理后的数据:", processed_data)
# 保存结果到excel
save_to_excel(processed_data, excel_path)
print(f"处理完成,结果已保存到: {excel_path}")
先区分说话人,只对老师进行检测(加快速度)
import re
import torch
import pandas as pd
from collections import Counter # 用于统计发言人发言次数
from transformers import BertTokenizer, BertModel
from sklearn.metrics.pairwise import cosine_similarity
from tqdm import tqdm # 导入 tqdm 库
# 检查是否有可用的 GPU
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
device = torch.device('cpu')
model.to(device)
# 定义行为类别与中文动词库
behavior_verb_dict = {
'讲授': ['解释', '说明', '阐述', '讲解', '介绍', '列举', '总结', '分析', '描述', '指出'],
'提问': ['问', '询问', '提问', '追问', '质问', '要求', '让你想', '让你回答'],
'指示': ['指示', '要求', '命令', '安排', '布置', '指引', '让你去做', '请完成'],
'反馈与评价': ['评价', '反馈', '表扬', '批评', '指出错误', '修正', '纠正', '总结', '认可']
}
# 函数:生成句子的BERT嵌入
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=8)
inputs = {k: v.to(device) for k, v in inputs.items()} # 将输入迁移到 GPU
outputs = model(**inputs)
embedding = outputs.last_hidden_state[:, 0, :].detach().cpu().numpy() # 将结果从 GPU 返回到 CPU
return embedding
# 函数:计算动词与行为类别动词库的相似度,并返回最佳行为类别及其相似度
def get_most_similar_behavior(verb, behavior_verb_dict, threshold=0.7):
verb_embedding = get_bert_embedding(verb)
max_similarity = 0
best_behavior = '未知行为'
for behavior, verb_list in behavior_verb_dict.items():
for behavior_verb in verb_list:
behavior_verb_embedding = get_bert_embedding(behavior_verb)
similarity = cosine_similarity(verb_embedding, behavior_verb_embedding)[0][0] # 计算余弦相似度
if similarity > max_similarity and similarity > threshold:
max_similarity = similarity
best_behavior = behavior
return best_behavior, max_similarity
# 函数:读取TXT文件并过滤开头
def extract_text_from_txt(txt_path):
with open(txt_path, 'r', encoding='utf-8') as file:
paragraphs = [line.strip() for line in file if line.strip()]
# 打印提取到的段落,调试用
print("提取到的段落内容:", paragraphs)
# 过滤掉特定开头的段落 "2024年5月7日 下午 6:33|46分钟 12秒"
filtered_paragraphs = []
start_flag = False
for para in paragraphs:
if para.startswith("说话人"): # 从检测到“说话人”开始处理
start_flag = True
if start_flag:
filtered_paragraphs.append(para)
return filtered_paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
# 改进的正则表达式,适应你的文档格式,匹配发言人和任意时间格式
match = re.match(r'(说话人\s*\d+)\s+(\d{1,2}:\d{2})', paragraph)
return match
# 函数:处理文档内容并进行语义分类和切分(根据发言人和动词变化进行切分)
def process_paragraphs(paragraphs, behavior_verb_dict):
results = []
current_speaker = None
current_time = None
current_content = ""
current_behavior = None
speaker_counter = Counter() # 统计发言人发言次数
# 使用 tqdm 显示进度条
for para in tqdm(paragraphs, desc="Processing paragraphs", unit="段"):
# 提取每个发言人、时间、内容
match = extract_speaker_time_content(para)
if match:
# 如果匹配到新的发言人,切分当前发言
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
# 更新当前发言人和时间,并清空内容
current_speaker, current_time = match.groups()
current_content = ""
current_behavior = None
# 统计发言人发言次数
speaker_counter[current_speaker] += 1
else:
# 如果没有发言人和时间,累积当前内容
current_content += " " + para.strip()
# 获取当前内容的行为类别
new_behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
# 如果动词(行为类别)发生变化,切分
if current_behavior and new_behavior != current_behavior:
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': current_behavior,
'语义相似度': similarity
})
# 更新当前行为类别
current_content = ""
# 更新当前的行为类别
current_behavior = new_behavior
# 保存最后一段发言
if current_speaker and current_content:
behavior, similarity = get_most_similar_behavior(current_content, behavior_verb_dict)
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
'行为类别': behavior,
'语义相似度': similarity
})
return results, speaker_counter
# 函数:替换发言人名称,将发言最多的替换为“老师”,其余替换为“学生1”、“学生2”依次类推
def replace_speaker_names(results, speaker_counter):
# 找到发言最多的发言人
most_common_speaker, _ = speaker_counter.most_common(1)[0]
speaker_mapping = {}
student_count = 1
for speaker in speaker_counter.keys():
if speaker == most_common_speaker:
speaker_mapping[speaker] = "老师"
else:
speaker_mapping[speaker] = f"学生{student_count}"
student_count += 1
# 替换发言人名称
for result in results:
result['发言人'] = speaker_mapping[result['发言人']]
return results
# 函数:将结果保存到Excel
def save_to_excel(data, excel_path):
df = pd.DataFrame(data)
df.to_excel(excel_path, index=False)
# 主程序
txt_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\数据\teacher-full.txt'
excel_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\切割\第二节发言切分结果.xlsx'
# 读取txt文档并过滤开头部分
paragraphs = extract_text_from_txt(txt_path)
# 处理文档内容,进行语义切分
processed_data, speaker_counter = process_paragraphs(paragraphs, behavior_verb_dict)
# 替换发言人名称
processed_data = replace_speaker_names(processed_data, speaker_counter)
# 打印处理后的数据,调试用
print("处理后的数据:", processed_data)
# 保存结果到excel
save_to_excel(processed_data, excel_path)
print(f"处理完成,结果已保存到: {excel_path}")
漏了保存学生的例子,只存了老师
只分析老师说的话,但是保存的时候把学生一起保存,加进度条
Reading TXT file: 618行 [00:00, 612495.24行/s]
Processing paragraphs: 100%|██████████| 408/408 [00:00<00:00, 398805.88段/s]
计算量少了一半
import re
import torch
import pandas as pd
from collections import Counter
from transformers import BertTokenizer, BertModel
from sklearn.metrics.pairwise import cosine_similarity
from tqdm import tqdm # 导入 tqdm 库
# 检查是否有可用的 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 加载BERT中文模型和分词器
bert_model_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\AI\深度学习\bert-base-chinese'
tokenizer = BertTokenizer.from_pretrained(bert_model_path)
model = BertModel.from_pretrained(bert_model_path)
model.to(device)
# 定义行为类别与中文动词库
behavior_verb_dict = {
'讲授': ['解释', '说明', '阐述', '讲解', '介绍', '列举', '总结', '分析', '描述', '指出'],
'提问': ['问', '询问', '提问', '追问', '质问', '要求', '让你想', '让你回答'],
'指示': ['指示', '要求', '命令', '安排', '布置', '指引', '让你去做', '请完成'],
'反馈与评价': ['评价', '反馈', '表扬', '批评', '指出错误', '修正', '纠正', '总结', '认可']
}
# 函数:生成句子的BERT嵌入
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=8)
inputs = {k: v.to(device) for k, v in inputs.items()} # 将输入迁移到 GPU
outputs = model(**inputs)
embedding = outputs.last_hidden_state[:, 0, :].detach().cpu().numpy() # 将结果从 GPU 返回到 CPU
return embedding
# 函数:计算动词与行为类别动词库的相似度,并返回最佳行为类别及其相似度
def get_most_similar_behavior(text, behavior_verb_dict, threshold=0.7):
text_embedding = get_bert_embedding(text)
max_similarity = 0
best_behavior = '未知行为'
for behavior, verb_list in behavior_verb_dict.items():
for verb in verb_list:
verb_embedding = get_bert_embedding(verb)
similarity = cosine_similarity(text_embedding, verb_embedding)[0][0] # 计算余弦相似度
if similarity > max_similarity and similarity > threshold:
max_similarity = similarity
best_behavior = behavior
return best_behavior, max_similarity
# 函数:读取TXT文件并过滤开头,带进度条
def extract_text_from_txt(txt_path):
paragraphs = []
with open(txt_path, 'r', encoding='utf-8') as file:
for line in tqdm(file, desc="Reading TXT file", unit="行"):
line = line.strip()
if line:
paragraphs.append(line)
# 过滤掉前面无关内容,从说话人部分开始
filtered_paragraphs = []
start_flag = False
for para in paragraphs:
if para.startswith("说话人"):
start_flag = True
if start_flag:
filtered_paragraphs.append(para)
return filtered_paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
# 改进的正则表达式,适应你的文档格式,匹配发言人和任意时间格式
match = re.match(r'(说话人\s*\d+)\s+(\d{1,2}:\d{2})', paragraph)
return match
# 函数:处理文档内容,划分发言人角色,带进度条
def process_paragraphs(paragraphs):
results = []
current_speaker = None
current_time = None
current_content = ""
speaker_counter = Counter() # 统计发言人发言次数
for para in tqdm(paragraphs, desc="Processing paragraphs", unit="段"):
match = extract_speaker_time_content(para)
if match:
# 保存之前的发言
if current_speaker and current_content:
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
})
# 更新当前发言人和时间,并清空内容
current_speaker, current_time = match.groups()
current_content = ""
# 统计发言人发言次数
speaker_counter[current_speaker] += 1
else:
# 累积发言内容
current_content += " " + para.strip()
# 保存最后一段发言
if current_speaker and current_content:
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content,
})
return results, speaker_counter
# 函数:替换发言人名称,将发言最多的替换为“老师”,其余替换为“学生1”、“学生2”依次类推
def replace_speaker_names(results, speaker_counter):
most_common_speaker, _ = speaker_counter.most_common(1)[0]
speaker_mapping = {}
student_count = 1
for speaker in speaker_counter.keys():
if speaker == most_common_speaker:
speaker_mapping[speaker] = "老师"
else:
speaker_mapping[speaker] = f"学生{student_count}"
student_count += 1
for result in results:
result['发言人'] = speaker_mapping[result['发言人']]
return results
# 函数:分析教师发言内容,带进度条
def analyze_teacher_content(results):
analyzed_data = []
current_behavior = None
for result in tqdm(results, desc="Analyzing Teacher Content", unit="发言"):
if result['发言人'] == '老师':
behavior, similarity = get_most_similar_behavior(result['内容'], behavior_verb_dict)
if current_behavior and behavior != current_behavior:
# 检测到行为类别变化
analyzed_data.append({
'发言人': result['发言人'],
'时间': result['时间'],
'内容': result['内容'],
'行为类别': behavior,
'语义相似度': similarity,
'行为变化': '是'
})
else:
analyzed_data.append({
'发言人': result['发言人'],
'时间': result['时间'],
'内容': result['内容'],
'行为类别': behavior,
'语义相似度': similarity,
'行为变化': '否'
})
current_behavior = behavior
else:
# 对学生的发言保持原样
analyzed_data.append({
'发言人': result['发言人'],
'时间': result['时间'],
'内容': result['内容'],
'行为类别': 'N/A',
'语义相似度': 'N/A',
'行为变化': 'N/A'
})
return analyzed_data
# 函数:将结果保存到Excel,带进度条
def save_to_excel(data, excel_path):
df = pd.DataFrame(data)
with tqdm(total=len(data), desc="Saving to Excel", unit="行") as pbar:
df.to_excel(excel_path, index=False)
pbar.update(len(data))
# 主程序
txt_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\数据\teacher-full.txt'
excel_path = r'D:\微信\WeChat Files\wxid_zrb1xqz427zg22\FileStorage\File\2023-11\课堂分析(客户)\课堂分析(客户)\TXT数据清洗\切割\test2.xlsx'
# 读取txt文档并过滤开头部分
paragraphs = extract_text_from_txt(txt_path)
# 处理文档内容,进行发言人角色划分
processed_data, speaker_counter = process_paragraphs(paragraphs)
# 替换发言人名称,将发言最多的替换为“老师”,其余替换为“学生”
processed_data = replace_speaker_names(processed_data, speaker_counter)
# 只分析“老师”的发言,学生的发言保持原样,并检测话语行为变化
analyzed_data = analyze_teacher_content(processed_data)
# 保存结果到excel
save_to_excel(analyzed_data, excel_path)
print(f"处理完成,结果已保存到: {excel_path}")
批量从word切割说话人
只保留区分老师学生存入excel的功能,其他先不要
定义filename为"E:\四1班—吴希敏"
批量读取filename 下面的所有word文件,实现excel的切分,
excel文件名和word文件名保持一致
import os
import re
from docx import Document
import pandas as pd
from tqdm import tqdm
from collections import Counter
# 函数:读取Word文档并过滤开头
def extract_text_from_docx(docx_path):
doc = Document(docx_path)
paragraphs = [p.text.strip() for p in doc.paragraphs if p.text.strip()]
# 过滤掉特定开头的段落
filtered_paragraphs = [para for para in paragraphs if not para.startswith("这一段") and not para.startswith("teacher-full_原文")]
return filtered_paragraphs
# 函数:提取发言人、时间和内容
def extract_speaker_time_content(paragraph):
match = re.match(r'(发言人\d+)\s+(\d{1,2}:\d{2})', paragraph)
return match
# 函数:处理文档内容,区分发言人
def process_paragraphs(paragraphs):
results = []
current_speaker = None
current_time = None
current_content = ""
speaker_counter = Counter()
for para in tqdm(paragraphs, desc="Processing paragraphs", unit="段"):
match = extract_speaker_time_content(para)
if match:
# 切分当前发言
if current_speaker and current_content:
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content
})
current_speaker, current_time = match.groups()
current_content = ""
speaker_counter[current_speaker] += 1
else:
current_content += " " + para.strip()
# 保存最后一段发言
if current_speaker and current_content:
results.append({
'发言人': current_speaker,
'时间': current_time,
'内容': current_content
})
return results, speaker_counter
# 函数:替换发言人名称
def replace_speaker_names(results, speaker_counter):
most_common_speaker, _ = speaker_counter.most_common(1)[0]
speaker_mapping = {}
student_count = 1
for speaker in speaker_counter.keys():
if speaker == most_common_speaker:
speaker_mapping[speaker] = "老师"
else:
speaker_mapping[speaker] = f"学生{student_count}"
student_count += 1
for result in results:
result['发言人'] = speaker_mapping[result['发言人']]
return results
# 函数:将结果保存到Excel
def save_to_excel(data, excel_path):
df = pd.DataFrame(data)
df.to_excel(excel_path, index=False)
# 函数:批量处理Word文件并生成Excel文件
def batch_process_word_to_excel(folder_path):
for file_name in os.listdir(folder_path):
if file_name.endswith('.docx'):
docx_path = os.path.join(folder_path, file_name)
excel_path = os.path.join(folder_path, file_name.replace('.docx', '.xlsx'))
print(f"Processing file: {file_name}")
# 读取word文档并过滤开头部分
paragraphs = extract_text_from_docx(docx_path)
# 处理文档内容,区分发言人
processed_data, speaker_counter = process_paragraphs(paragraphs)
# 替换发言人名称
processed_data = replace_speaker_names(processed_data, speaker_counter)
# 保存结果到excel
save_to_excel(processed_data, excel_path)
print(f"Saved results to: {excel_path}")
# 定义主程序
if __name__ == "__main__":
filename = r'E:\四1班—吴希敏'
batch_process_word_to_excel(filename)