前言
为了不搞忘,先把代码记在这里
由【2024泰迪杯】C 题:竞赛论文的辅助自动评阅 问题分析及Python 代码实现 草草填充而来,里面还有很多bug,待改进,大佬们可在评论区回复~
问题三
# 01
import requests
import json
import os
import time #增加时间延迟机制
# 改进2:定义delayed_completion函数,增加延迟以遵守API速率限制
def delayed_completion(user_message, delay_seconds=1):
time.sleep(3) # 等待指定的秒数
return AI_chat(user_message)
# 通过AI API生成文本
def AI_chat(user_message):
MOONSHOT_API_KEY = os.getenv('MOONSHOT_API_KEY')
if not MOONSHOT_API_KEY:
raise ValueError("MOONSHOT_API_KEY environment variable is not set.")
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {MOONSHOT_API_KEY}',
}
data = {
"model": "moonshot-v1-32k",
"messages": [
{"role": "user", "content": user_message}
],
"temperature": 0.5,
}
response = requests.post('https://api.moonshot.cn/v1/chat/completions', headers=headers, data=json.dumps(data))
# 改进1:增加检查机制——检查响应状态码
if response.status_code != 200:
raise Exception(f"Request failed with status code {response.status_code}: {response.text}")
try:
response_json = response.json()
assistant_message = response_json['choices'][0]['message']['content']
return assistant_message
except KeyError as e:
raise Exception(f"Failed to parse response: {e}. Response content: {response.text}")
# 02
from pdfminer.high_level import extract_text
import re
# 2.读取PDF文件内容
# 使用正则表达式提取摘要部分和正文部分
def extract_abstract_and_body(pdf_path):
full_text = extract_text(pdf_path)
# 去除文本中的空格和空行
full_text = full_text.replace(' ','').replace('\n','')
# 移除掉目录项,假设目录项以数字加页码的形式出现,例如 "1 引言...2"
full_text = re.sub(r'\d+\s+.*\.\.\.\s+\d+','',full_text)
# 修复可能的分页导致关键词被割断的问题
repaired_text = full_text.replace('-\n','').replace('\n',' ')
# 找到‘摘要’和‘关键词’之间的文本(填空)
abstract_match = re.search(r'摘要([\s\S]*?)关键词|一、引言|引言', full_text)
if abstract_match:
abstract = abstract_match.group(1).strip()
else:
abstract = ''
# 找到正文起始关键词后的所有文本作为正文(填空)
body_start_keywords = ['一、引言', '引言', '正文']
body_match = None
for keyword in body_start_keywords:
body_match = re.search(rf'({keyword})([\s\S]*)', full_text)
if body_match:
break
if body_match:
body = body_match.group(2).strip()
else:
# 如果找不到明确的正文起始关键词,则假设关键词之后就是正文
start_index = full_text.find('关键词') + 3 if '关键词' in full_text else 0
body = full_text[start_index:].strip()
# 清除摘要与正文之间可能多余的标题等内容
return abstract.strip(),body.strip()
# 3.计算摘要与正文的相关性和一致性,并进行质量评价打分
def evaluate_summary(summary, content):
# 构建提示词
user_message = f"请计算以下论文摘要与正文的相关性和一致性,并进行质量评价打分(输出1到10分之间),要求只输出最终的评分数字,如9:\n摘要: {summary}\n正文: {content}"
# 使用kimi_chat函数获取结果
result = delayed_completion(user_message) # 改进2:使用带有延迟的函数
# 解析返回的结果以获取分数
try:
number = re.search(r'\d+',result).group(0) # 使用正则表达式提取整数数字
score = int(number) # 将提取的数字转换为整数类型
return score
except ValueError:
return "无法解析分数,请确保返回的内容包含一个整数值。"
import os#引用os库
#遍历文件夹的所有PDF文件
file_list=[]#新建一个空列表用于存放文件名
file_dir="D:\我\学习\实验室\比赛\泰迪杯\C题\资料\示例数据" #遍历的文件夹路径
for files in os.walk(file_dir):#遍历指定文件夹及其下的所有子文件夹
for file in files[2]:#遍历每个文件夹里的所有文件,(files[2]:母文件夹和子文件夹下的所有文件信息,files[1]:子文件夹信息,files[0]:母文件夹信息)
if os.path.splitext(file)[1]=='.PDF' or os.path.splitext(file)[1]=='.pdf':#检查文件后缀名,逻辑判断用==
# file_list.append(file)#筛选后的文件名为字符串,将得到的文件名放进去列表,方便以后调用
file_list.append(file_dir+'\\'+file)#给文件名加入文件夹路径
for file in file_list:#循环遍历文件列表
paper_file_path = file # 论文
# 读取摘要和正文
summary_paper, content_paper = extract_abstract_and_body(paper_file_path)
# 计算相关性和一致性,并进行质量评价打分
score = evaluate_summary(summary_paper,content_paper)
print(f"论文摘要的质量评价分数是: {score}")
问题四
import pdfminer
from pdfminer.high_level import extract_text
import spacy
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from spacy.tokens import Doc
import jieba.analyse
import matplotlib.pyplot as plt
from wordcloud import WordCloud
#1.准备
#(1)载入中文NLP模型
nlp = spacy.load('zh_core_web_sm')
#(2)使用哈工大中文停用词库
stop_words = [line.strip() for line in open("D:\我\学习\实验室\比赛\泰迪杯\C题\资料\data\问题四\停用词库.txt", encoding='utf-8').readlines()]
#(3)读取PDF文件函数
def read_pdf(file_path):
text = extract_text(file_path)
# 去除文本中的空格和空行
full_text = text.replace(' ','').replace('\n','')
return full_text
#2.实现函数
#(1)评价语法结构函数
def evaluate_text_flow(text):
doc = nlp(text)
sentences = list(doc.sents)
flow_score = 0
for i in range(len(sentences)-1):
current_sent = sentences[i]
next_sent = sentences[i+1]
# 检查当前句子和下一句之间的连接词
if any(token.dep_ == 'cc' for token in current_sent):
flow_score += 1
# 检查当前句子的结尾和下一句的开头是否有关联
if current_sent[-1].text in next_sent[0].text:
flow_score += 1
# 最后,必须确保分数介于0到10之间
flow_score = min(10, flow_score)
# 标准化分数
if len(sentences) > 1:
norm_score = (flow_score / (len(sentences)-1)) * 10
return norm_score
else:
# 如果只有一句话,则不适用流程评分标准
return 10
#(2)写作规范性评价函数
def evaluate_writing_standard(text):
doc = nlp(text)
standard_score = 0
# 检查标点符号的使用是否规范
for token in doc:
if token.text in ['。', '!', '?', ';', ':', ',']:
standard_score += 1
# 检查是否有错别字
for token in doc:
if token.text not in token.vocab:
standard_score -= 1
return standard_score
#(3)篇章结构评价函数
def evaluate_structure(text):
doc = nlp(text)
structure_score = 0
# 检查是否有明确的开头和结尾
if len(list(doc.sents)) > 0:
structure_score += 1
if len(list(doc.sents)) > 1:
structure_score += 1
# 检查是否有明确的小标题
if any(token.text == '##' for token in doc):
structure_score += 1
# 将分数归一化到0-10分之间
return min((structure_score / len(list(doc.sents))) * 10,10)
#(4)定义评价论文立意的函数
def evaluate_intention(prob_keywords,paper_keywords):
score = 0
# 检查论文关键词是否与赛题关键词相关
for keyword in paper_keywords:
if keyword in prob_keywords:
score += 1
return score
problem_pdf = "D:\我\学习\实验室\比赛\泰迪杯\C题\资料\data\问题四\\2020泰迪杯C题题目.pdf" # 赛题题目
paper_pdf = "D:\我\学习\实验室\比赛\泰迪杯\C题\资料\C题-全部数据\附件1\C001.pdf" # 论文
# 读取pdf文件
problem_text = read_pdf(problem_pdf)
paper_text = read_pdf(paper_pdf)
#3.评价
#(1)评价语法结构
flow_score = evaluate_text_flow(paper_text)
print("语法结构评分:", flow_score)
#(2)评价写作规范性
standard_score = evaluate_writing_standard(paper_text)
print("写作规范性评分:", standard_score)
#(3)评价篇章结构
structure_score = evaluate_structure(paper_text)
print("篇章结构评分:", structure_score)
#(4)评价论文立意
prob_keywords = jieba.analyse.extract_tags(problem_text, topK=5)
paper_keywords = jieba.analyse.extract_tags(paper_text, topK=5)
intention_score = evaluate_intention(prob_keywords, paper_keywords)
print("论文立意评分:", intention_score)
&spm=1001.2101.3001.11974&articleId=138278285&d=1&t=3&u=4f827d25620242d9a0db288de9a8daed)
331


&spm=1001.2101.3001.11976&articleId=138278285&d=1&t=3&u=1c61442483084ee0b00fc6eb1e572d3c)

被折叠的 条评论
为什么被折叠?



