Python 运维

相似文章推荐

2017-12-03  本文已影响13人  羽恒

知识点普及

余弦相似度公式

样例代码

#!/usr/bin/env python
# coding=utf-8



import os 
import codecs
import numpy as np 


# 生成分词字符串
filePaths = []
fileContents = []
for root,dirs,files in os.walk('../data/input/SogouC.mini/Sample/'):
    for name in files:
        filePath = os.path.join(root,name)
        filePaths.append(filePath)
        f = codecs.open(filePath,'r','utf-8')
        fileContent = f.read()
        f.close()
        fileContents.append(fileContent)

import pandas as pd 

# 对分词文档做DataFrame运算 
corpos = pd.DataFrame({
    'filePath':filePaths,
    'fileContent':fileContents
})


import re 
# 匹配中文分词正则表达式
zhPattern = re.compile(u'[\u4e00-\u9fa5]+')



import jieba 
segments = []
filePaths = []

for index, row in corpos.iterrows():
    filePath = row['filePath']
    fileContent = row['fileContent']
    segs = jieba.cut(fileContent)
    for seg in segs:
        if zhPattern.search(seg):
            segments.append(seg)
    filePaths.append(seg)
    # 分词完成后添加空格
    row['fileContent'] = ' '.join(segments)

from sklearn.feature_extraction.text import CountVectorizer

stopwords = pd.read_csv('../data/input/StopwordsCN.txt',
                       encoding = 'utf-8',
                       index_col = False,
                       quoting = 3,
                       sep = '\t')
# 提取文章关键字
countVectorizer = CountVectorizer(
    stop_words = list(stopwords['stopword'].values),
    min_df = 0, token_pattern = r"\b\w+\b"
    )
# 对文档关键字做向量化处理,生成文档向量化矩阵
textVector = countVectorizer.fit_transform(
    corpos['fileContent']
    )
from sklearn.metrics import pairwise_distances

#计算两两之间的余弦相似度
distance_matrix = pairwise_distances(
    textVector,
    metric = 'cosine'
    )

m = 1 - pd.DataFrame(distance_matrix)
m.columns = filePaths
m.index   = filePaths

#每篇文章最相似的五篇文章
sort = np.argsort(distance_matrix,axis = 1)[:,1:6]


similarity5 = pd.Index(filePaths)[sort].values

similarityDF = pd.DataFrame({
    'filePath':corpos.filePath,
    's1':similarity5[:,0],
    's2':similarity5[:,1],
    's3':similarity5[:,2],
    's4':similarity5[:,3],
    's5':similarity5[:,4],
})
上一篇下一篇

猜你喜欢

热点阅读