首页 > 编程语言 >python3 - 使用 jieba3k 对直播平台房间标题进行分词

python3 - 使用 jieba3k 对直播平台房间标题进行分词

时间:2022-10-31 12:07:17浏览次数:79  
标签:__ hero name db self list python3 分词 jieba3k


python3 安装jieba:


pip3 install jieba


或者,先下载

​ http://pypi.python.org/pypi/jieba/​​ ,解压后运行 python setup.py install

参考:​​https://github.com/fxsjy/jieba​


实例:



得到标签和创建mydict



import requests

from pyquery import PyQuery as pq
from db import MongoClient
from config import MY_DICT

db = MongoClient()

def get_label(url):
r = requests.get(url)
r.encoding = 'utf-8' # 通过r.encoding设置页面编码
doc = pq(r.text)
table = doc.find('body > div.body-wrapper > div.content-wrapper > div > div.main-content > table:nth-child(154) > tr').items()
id = 0
for tr in table:
if tr.find('td'): # 去掉th
'''
页面table有问题,单独修改一下
db.getCollection('hero').update(
// query
{
"id" : 2
},

// update
{ '$set' : {'hero_name' : '幻翎', 'hero_name_list' : ['幻翎', '洛'], "join_time" : "2017年4月18日"}
},

// options
{
"multi" : false, // update only one document
"upsert" : false // insert a new document, if no existing document match the query
}
);
'''
id += 1
hero_name = tr.find('td:nth-child(2)').text().strip()
hero_name_list = []
hero_name_list.append(tr.find('td:nth-child(2)').text().strip())
hero_name_list.append(tr.find('td:nth-child(3)').text().strip())
join_time = tr.find('td:nth-child(6)').text().strip()
msg = {
'id' : id,
'hero_name' : hero_name,
'hero_name_list' : hero_name_list,
'join_time' : join_time
}
db.save(msg)

def make_mydict():
with open(MY_DICT, mode='w', encoding='utf-8') as f:
for name in db.get_hero_name_list():
print(name, file=f) # 直接换行

if __name__ == '__main__':
# get_label('http://baike.baidu.com/item/英雄联盟/4615671#4')
make_mydict() # 创建词典
print('ok...')


分词器



import jieba
import jieba.analyse

from db import MongoClient
from config import MY_DICT

class Tokenizer(object):
def __init__(self):
self._db = MongoClient()
# 载入自己的词库
jieba.load_userdict(MY_DICT)

def get_hero_list(self):
hero_list = []
with open(MY_DICT, mode='r', encoding='utf-8') as f:
for hero in f:
hero_list.append(hero.strip())
return hero_list

def participle(self):
hero_list = self.get_hero_list()
print('/'.join(hero_list))
for room in self._db.get_rooms():
# 分词 [默认精确]
msg = jieba.lcut(room['r_name'])
label_list = set([w for w in msg if w in hero_list]) # 去重复
self._db.set_label(query={'r_id' : room['r_id']},
data={'$set' : {'r_label' : list(label_list)}})
print(msg, label_list)

if __name__ == '__main__':
# 分词器
tokenizer = Tokenizer()
tokenizer.participle()


db



import pymongo

from config import *

class MongoClient(object):
def __init__(self):
self._client = pymongo.MongoClient(MONGO_URL)

def get_rooms(self):
db = self._client[MONGO_DB]
for room in db[MONGO_TABLE].find(): # 去掉limit
yield {
'r_id' : room['r_id'],
'r_name' : room['r_name']
}
def set_label(self, **kwargs):
self._client[MONGO_DB][MONGO_TABLE].\
update(kwargs['query'], kwargs['data'], upsert=False)

def save(self, msg):
try:
self._client[MONGO_DB][MONGO_HERO_NAME].insert(msg)
except Exception as e:
print("e: ", e)
def get_hero_name_list(self):
for hero_name in self._client[MONGO_DB][MONGO_HERO_NAME].find():
for name in hero_name['hero_name_list']:
yield name




问题:


1. 运行的文件名和import xxx 的包名重复


import jieba
jieba.cut("我来到北京清华大学")


AttributeError: 'module' object has no attribute 'cut'


不要将运行的文件名命名为jieba.py,自己撸自己当然出错了



标签:__,hero,name,db,self,list,python3,分词,jieba3k
From: https://blog.51cto.com/u_11290086/5808982

相关文章

  • Centos8 升级python3.6版本到python3.9
    下载Python3.9.51:wgethttps://www.python.org/ftp/python/3.9.5/Python-3.9.5.tgz2:tarzxvfPython-3.9.5.tgz安装必须的包3:dnf-yinstallgcczlib*libffi-dev......
  • Selenium4+Python3系列(五) - 多窗口处理之句柄切换
    写在前面感觉到很惭愧呀,因为居然在Selenium+Java系列中没有写过多窗口处理及句柄切换的文章,不过也无妨,不管什么语言,其思路是一样的,下面我们来演示,使用python语言来实现窗......
  • Java中String的分词方法split的使用
    在java.lang包中有String.split()方法,返回是一个数组1、如果用“.”作为分隔的话,必须是如下写法:String.split("\\."),这样才能正确的分隔开,不能用String.split(".");2、......
  • Python3.11正式版,它来了!
    转载请注明出处❤️作者:测试蔡坨坨原文链接:caituotuo.top/b055fbf2.html你好,我是测试蔡坨坨。就在前几天,2022年10月24日,Python3.11正式版发布了!Python官方在2020年1月......
  • python3使用libpcap库进行抓包及数据处理
    python版本:python3.9libpcap版本:1.11.0b7pythonlibpcap库是底层绑定c语言libpcap库的开发包,旨在提供python应用可访问的unixclibpcap库API(以及为win32系统提供的Npca......
  • 第1章 欢迎来到 Python3 玩转机器学习
     1-1导学                                               ......
  • python 安装 jieba分词第三方库 报错 以及解决
      在安装jieba第三方库的时候,Python报错pip._vendor.urllib3.exceptions.ReadTimeoutError:HTTPSConnectionPool(host='files.pythonhosted.org',port=443):Readt......
  • python3.9不支持win7
    安装:Anaconda3-2022.10-Windows-x86_64.exe会报错:FailedtocreateAnacondamenus详细信息:ErrorloadingPythonDLLxxxpython39.dll,LoadLibrary:PyInstaller:Forma......
  • 文本挖掘与NLP笔记——代码向:分词
    分词:jieba.cutwords=jieba.cut("我来到北京大学",cut_all=True)print('全模式:'+'/'.join([wforwinwords]))#全模式words=jieba.cut("我来到北京大学",cut_a......
  • python3 使用位图排序
    代码frombitmapimportBitMapa=[1,5,3,4,7,8,15,6,9]print(a)bm=BitMap(max(a))#print(dir(bm))print(bm.tostring())foriina:bm.set(i)print(bm......