【python】读取xlsx文件,并测试文件内的Rouge-L指标

解决问题:读取xlsx文件内的中文文本,并测试参考答案和模型生成答案之间的Rouge-L指标。

import pandas as pd
import jieba
from rouge import Rouge
import sys

# 增加递归深度限制
sys.setrecursionlimit(10000)

def preprocess_text(text):
    # 使用 jieba 进行中文分词
    words = jieba.lcut(text)
    return ' '.join(words)

def calculate_rouge_l(reference, candidate):
    rouge = Rouge()
    
    # 预处理文本
    reference = preprocess_text(reference)
    candidate = preprocess_text(candidate)


    print("----------------")
    print(reference)
    print("----------------")
    print(candidate)

    # 计算ROUGE-L
    scores = rouge.get_scores(candidate, reference)
    return scores[0]['rouge-l']['r']  # 返回ROUGE-L的Recall得分

def main():
    # 读取xlsx文件
    file_path = '文件路径'
    df = pd.read_excel(file_path)

    # 打印列名以进行调试
    print("Columns in the dataframe:", df.columns)

    # 假设数据有一列 'reference' 和五列 'candidate1', 'candidate2', 'candidate3', 'candidate4', 'candidate5'
    references = df['参考答案']
    candidate_columns = ['one', 'two', 'three', 'four', 'five']

    # 计算每个reference与每个candidate的ROUGE-L指标
    for candidate in candidate_columns:
        if candidate not in df.columns:
            print(f"Column {candidate} not found in the dataframe.")
            continue

        rouge_scores = []
        for ref, cand in zip(references, df[candidate]):
            if pd.isna(ref) or pd.isna(cand):
                rouge_scores.append(0)
                continue

            rouge_score = calculate_rouge_l(ref, cand)
            rouge_scores.append(rouge_score)

        # 将ROUGE-L指标添加到DataFrame中
        df[f'ROUGE-L_{candidate}'] = rouge_scores

    # 保存结果到新的xlsx文件
    output_path = '文件路径'
    df.to_excel(output_path, index=False)

    print("Saved ROUGE scores to:", output_path)

if __name__ == "__main__":
    main()

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值