使用python中的去重算法对Excel文件的指定一列的中文新闻正文进行文本相似度计算和去重删除相似度高于08的文本
首先,需要安装python中的一些库,如pandas、jieba、gensim和simhash等。
然后,可以按照以下步骤进行操作:
- 读取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'[^\u4e00-\u9fa5]', '', text)
# 分词
words = jieba.cut(text)
# 去除停用词
words = [word for word in words if word not in stopwords]
# 拼接成字符串返回
return ' '.join(words)
# 对每条新闻正文进行预处理
content = content.apply(preprocess)
- 计算文本的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)
``
原文地址: https://www.cveoy.top/t/topic/diKR 著作权归作者所有。请勿转载和采集!