Python使用gensim计算文档相似性
pre_file.py
#-*-coding:utf-8-*- import MySQLdb import MySQLdb as mdb import os,sys,string import jieba import codecs reload(sys) sys.setdefaultencoding('utf-8') #连接数据库 try: conn=mdb.connect(host='127.0.0.1',user='root',passwd='kongjunli',db='test1',charset='utf8') except Exception,e: print e sys.exit() #获取cursor对象操作数据库 cursor=conn.cursor(mdb.cursors.DictCursor) #cursor游标 #获取内容 sql='SELECT link,content FROM test1.spider;' cursor.execute(sql) #execute()方法,将字符串当命令执行 data=cursor.fetchall()#fetchall()接收全部返回结果行 f=codecs.open('C:\Users\kk\Desktop\hello-result1.txt','w','utf-8') for row in data: #row接收结果行的每行数据 seg='/'.join(list(jieba.cut(row['content'],cut_all='False'))) f.write(row['link']+' '+seg+'\r\n') f.close() cursor.close() #提交事务,在插入数据时必须
jiansuo.py
#-*-coding:utf-8-*- import sys import string import MySQLdb import MySQLdb as mdb import gensim from gensim import corpora,models,similarities from gensim.similarities import MatrixSimilarity import logging import codecs reload(sys) sys.setdefaultencoding('utf-8') con=mdb.connect(host='127.0.0.1',user='root',passwd='kongjunli',db='test1',charset='utf8') with con: cur=con.cursor() cur.execute('SELECT * FROM cutresult_copy') rows=cur.fetchall() class MyCorpus(object): def __iter__(self): for row in rows: yield str(row[1]).split('/') #开启日志 logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',level=logging.INFO) Corp=MyCorpus() #将网页文档转化为tf-idf dictionary=corpora.Dictionary(Corp) corpus=[dictionary.doc2bow(text) for text in Corp] #将文档转化为词袋模型 #print corpus tfidf=models.TfidfModel(corpus)#使用tf-idf模型得出文档的tf-idf模型 corpus_tfidf=tfidf[corpus]#计算得出tf-idf值 #for doc in corpus_tfidf: #print doc ### ''' q_file=open('C:\Users\kk\Desktop\q.txt','r') query=q_file.readline() q_file.close() vec_bow=dictionary.doc2bow(query.split(' '))#将请求转化为词带模型 vec_tfidf=tfidf[vec_bow]#计算出请求的tf-idf值 #for t in vec_tfidf: # print t ''' ### query=raw_input('Enter your query:') vec_bow=dictionary.doc2bow(query.split()) vec_tfidf=tfidf[vec_bow] index=similarities.MatrixSimilarity(corpus_tfidf) sims=index[vec_tfidf] similarity=list(sims) print sorted(similarity,reverse=True)
encodings.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="Encoding"> <file url="PROJECT" charset="UTF-8" /> </component> </project>
misc.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectLevelVcsManager" settingsEditedManually="false"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.11 (C:\Python27\python.exe)" project-jdk-type="Python SDK" /> </project>
modules.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/爬虫练习代码.iml" filepath="$PROJECT_DIR$/.idea/爬虫练习代码.iml" /> </modules> </component> </project>

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 시스템과 함께 제공되는 Python 통역사를 제거하는 문제와 관련하여 많은 Linux 배포판이 설치 될 때 Python 통역사를 사전 설치하고 패키지 관리자를 사용하지 않습니다 ...

Go 또는 Rust를 사용하여 Python 스크립트를 호출하여 실제 병렬 실행을 달성하는 방법은 무엇입니까? 최근에 나는 파이썬을 사용하고 있습니다 ...

Pythonasyncio에 대해 ...

Pylance 유형 감지 문제 솔루션 Python 프로그래밍에서 사용자 정의 데코레이터를 사용할 때 Decorator는 행을 추가하는 데 사용할 수있는 강력한 도구입니다 ...

Python의 TQDM 라이브러리를 사용할 때 Python의 TQDM 인쇄로 인쇄 된 중복 진행 막대 문제를 피하십시오. 루프 내부에서 인쇄를 사용하는 경우 ...

Python의 HTTPX 라이브러리를 사용하여 HTTP/2를 보내십시오 ...

파이썬 비동기 라이브러리 사이의 호환성 문제 파이썬에서 비동기 프로그래밍은 동시성과 I/O의 프로세스가되었습니다 ...

Python 3.6에 피클 파일 로딩 3.6 환경 오류 : ModulenotFounderRor : nomodulename ...
