使用 Python 对 Excel 文件的指定一列中文新闻正文进行文本相似度计算和去重,删除相似度高于 0.8 的文本内容

本文将介绍如何使用 Python 对 Excel 文件中的中文新闻正文进行文本相似度计算和去重,删除相似度高于 0.8 的内容。

第一步:安装必要的 Python 库

首先,需要安装以下 Python 库:

  • pandas: 用于读取和处理 Excel 文件。
  • jieba: 用于中文分词。
  • gensim: 用于计算 Simhash 值。
  • simhash: 用于计算文本相似度。

可以使用 pip install pandas jieba gensim simhash 命令安装这些库。

第二步:读取 Excel 文件并选择需要去重的列

使用 pandas 库读取 Excel 文件,并选择需要去重的列,例如 '新闻正文' 列。

import pandas as pd

df = pd.read_excel('news.xlsx')
content = df['新闻正文']

第三步:对文本进行分词和预处理

对文本进行分词和预处理,包括去除停用词、标点符号等。

import jieba
import re

stopwords = [line.strip() for line in open('stopwords.txt', 'r', encoding='utf-8').readlines()]

def preprocess(text):
    # 使用正则表达式去除标点符号等非中文字符
    text = re.sub(r'[^一-龥]', '', text)
    # 分词
    words = jieba.cut(text)
    # 去除停用词
    words = [word for word in words if word not in stopwords]
    # 拼接成字符串返回
    return ' '.join(words)

# 对每条新闻正文进行预处理
content = content.apply(preprocess)

第四步:计算文本的 Simhash 值并进行去重

使用 gensim 库计算文本的 Simhash 值,并使用 simhash 库计算文本相似度。将相似度高于 0.8 的文本进行去重。

from gensim.similarities import Simhash

# 定义 Simhash 函数
def get_simhash(text):
    return Simhash(text).value

# 计算每条新闻正文的 Simhash 值
simhash_values = content.apply(get_simhash)

# 建立相似度矩阵,判断相似度是否高于 0.8
similarities = []
for i in range(len(content)):
    for j in range(i+1, len(content)):
        sim = Simhash(content[i]).distance(Simhash(content[j]))
        if sim < 3:
            similarities.append((i, j, sim))

# 删除相似度高于 0.8 的文本
for i, j, sim in similarities:
    if sim > 0.8:
        df.drop(j, inplace=True)

# 将去重后的结果保存到新的 Excel 文件中
df.to_excel('news_deduped.xlsx', index=False)

总结

通过以上步骤,即可使用 Python 对 Excel 文件中的中文新闻正文进行文本相似度计算和去重,删除相似度高于 0.8 的内容。该方法简单易用,且效率较高,适用于大规模文本数据处理。

Python Excel 文本相似度去重:高效处理中文新闻正文

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

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