jieba入门

最简单的词频统计(数据源是全职高手小说)
  1. import jieba
  2. from collections import Counter
  3. if __name__ == "__main__":
  4. #file_path_read=input("输入待识别文本位置")
  5. file_path_read = 'D:\\New_desktop\\12.txt'
  6. try:
  7. with open(file_path_read, 'r', encoding='utf-8') as f:
  8. sentence=f.read()
  9. except FileNotFoundError:
  10. print('无法打开指定的文件!')
  11. except LookupError:
  12. print('指定了未知的编码!')
  13. except UnicodeDecodeError:
  14. print('读取文件时解码错误!')
  15. seg1 = jieba.cut(sentence, cut_all=False)
  16. frequency = Counter()
  17. for word in seg1:
  18. if len(word)>1:
  19. frequency[word] += 1
  20. for (k, v) in frequency.most_common(100):
  21. print(k," "*int(20-len(k)),v)

image.png

训练词向量和jieba结合

同样的训练数据源来源于全职高手

  1. import jieba
  2. novel = open('D:\\New_desktop\\12.txt','r',encoding='UTF-8')
  3. content=novel.read()
  4. novel_segmented = open('D:\\New_desktop\\1.txt','w')
  5. cutword = jieba.cut(content,cut_all=False)
  6. seg = ' '.join(cutword).replace(',','').replace('。','').replace('“','').replace('”','').replace(':','').replace('…','')\
  7. .replace('!','').replace('?','').replace('~','').replace('(','').replace(')','').replace('、','').replace(';','')
  8. try:
  9. with open('D:\\New_desktop\\1.txt', 'w+', encoding='utf-8') as f:
  10. f.write(seg)
  11. except FileNotFoundError:
  12. print('无法打开指定的文件!')
  13. except LookupError:
  14. print('指定了未知的编码!')
  15. except UnicodeDecodeError:
  16. print('读取文件时解码错误!')
  17. novel.close()
  18. novel_segmented.close()
  19. # 训练word2vec模型,生成词向量
  20. from gensim.models import word2vec
  21. # 训练word2vec模型,生成词向量
  22. s = word2vec.LineSentence('D:\\New_desktop\\1.txt')
  23. # 这里如果报编码错误,notepad++打开,然后转码为对应编码即可。
  24. model = word2vec.Word2Vec(s,size=200,window=5,min_count=0,workers=4)
  25. model.save('D:\\New_desktop\\3.txt')
  26. print("1 2",model.wv.similarity("叶修","苏沐橙"))
  27. print("1 3",model.wv.similarity("叶修","千机"))
  28. for i in model.most_similar(u"叶修",topn=20):
  29. print (i[0],i[1])
  1. seg1 = jieba.cut(sentence, cut_all=False)
  2. print(type(seg1))
  3. print(seg1)
  4. seg = ' '.join(seg1).replace(',', '').replace('。', '').replace('“', '').replace('”', '').replace(':', '').replace('…', '') \
  5. .replace('!', '').replace('?', '').replace('~', '').replace('(', '').replace(')', '').replace('、', '').replace(';', '').replace(',',' ')

利用正则表达式去除不必要的标点
image.png

jieba关键词抽取

先前是使用全本的全职高手进行数据分析,字太多了。。。之前还行,在这个环节就不行了,运行了很久,所以随机抽取了一段进行分析测试,感觉第一个算法的结果和算法性能都更好一些

  1. from jieba import analyse
  2. # 引入TF-IDF关键词抽取接口
  3. tfidf = analyse.extract_tags
  4. textrank = analyse.textrank
  5. filename = "D:\\New_desktop\\123.txt"
  6. # 基于TF-IDF算法进行关键词抽取
  7. content = open(filename, 'rb').read()
  8. keywords = tfidf(content)
  9. print ("keywords by tfidf:")
  10. # 输出抽取出的关键词
  11. for keyword in keywords:
  12. print (keyword + "/")
  13. print ("\nkeywords by textrank:")
  14. # 基于TextRank算法进行关键词抽取
  15. keywords = textrank(content)
  16. # 输出抽取出的关键词
  17. for keyword in keywords:
  18. print (keyword)
  19. print("end")

image.png

标注词性
  1. import jieba
  2. import jieba.analyse
  3. import jieba.posseg
  4. '''
  5. 带词性标注,对句子进行分词,不排除停词等
  6. :param sentence:输入字符
  7. :return:
  8. '''
  9. filename = "D:\\New_desktop\\123.txt"
  10. f = open(filename,"r",encoding='utf-8')
  11. result = list()
  12. for line in f.readlines():
  13. line = line.strip()
  14. if not len(line):
  15. continue
  16. result.append(line)
  17. f.close
  18. content=""
  19. for sentence in result:
  20. sentence.encode('utf-8')
  21. data=sentence.strip()
  22. if len(data)!=0:
  23. content+=data
  24. cutword = jieba.cut(content,cut_all=False)
  25. seg = ''.join(cutword).replace(',','').replace('。','').replace('“','').replace('”','').replace(':','').replace('…','')\
  26. .replace('!','').replace('?','').replace('~','').replace('(','').replace(')','').replace('、','').replace(';','').replace(',','')
  27. print(seg)
  28. sentence_seged = jieba.posseg.cut(seg.strip())
  29. outstr = ''
  30. for x in sentence_seged:
  31. outstr += "{}/{},".format(x.word, x.flag)
  32. # 上面的for循环可以用python递推式构造生成器完成
  33. # outstr = ",".join([("%s/%s" %(x.word,x.flag)) for x in sentence_seged])
  34. print(outstr)

image.png

jieba并行计算提高速度

看教程看到的,没用过

  1. import sys
  2. import time
  3. sys.path.append("../../")
  4. import jieba
  5. jieba.enable_parallel()
  6. url = sys.argv[1]
  7. content = open(url,"rb").read()
  8. t1 = time.time()
  9. words = "/ ".join(jieba.cut(content))
  10. t2 = time.time()
  11. tm_cost = t2-t1
  12. log_f = open("1.log","wb")
  13. log_f.write(words.encode('utf-8'))
  14. print('speed %s bytes/second' % (len(content)/tm_cost))

chineseanlyse

没看懂在干嘛,但还是存下来了

  1. from __future__ import unicode_literals
  2. import sys,os
  3. sys.path.append("../")
  4. from whoosh.index import create_in,open_dir
  5. from whoosh.fields import *
  6. from whoosh.qparser import QueryParser
  7. from jieba.analyse.analyzer import ChineseAnalyzer
  8. analyzer = ChineseAnalyzer()
  9. schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT(stored=True, analyzer=analyzer))
  10. if not os.path.exists("tmp"):
  11. os.mkdir("tmp")
  12. ix = create_in("tmp", schema) # for create new index
  13. #ix = open_dir("tmp") # for read only
  14. writer = ix.writer()
  15. writer.add_document(
  16. title="document1",
  17. path="/a",
  18. content="This is the first document we’ve added!"
  19. )
  20. writer.add_document(
  21. title="document2",
  22. path="/b",
  23. content="The second one 你 中文测试中文 is even more interesting! 吃水果"
  24. )
  25. writer.add_document(
  26. title="document3",
  27. path="/c",
  28. content="买水果然后来世博园。"
  29. )
  30. writer.add_document(
  31. title="document4",
  32. path="/c",
  33. content="工信处女干事每月经过下属科室都要亲口交代24口交换机等技术性器件的安装工作"
  34. )
  35. writer.add_document(
  36. title="document4",
  37. path="/c",
  38. content="咱俩交换一下吧。"
  39. )
  40. writer.commit()
  41. searcher = ix.searcher()
  42. parser = QueryParser("content", schema=ix.schema)
  43. for keyword in ("水果世博园","你","first","中文","交换机","交换"):
  44. print("result of ",keyword)
  45. q = parser.parse(keyword)
  46. results = searcher.search(q)
  47. for hit in results:
  48. print(hit.highlights("content"))
  49. print("="*10)
  50. for t in analyzer("我的好朋友是李明;我爱北京天安门;IBM和Microsoft; I have a dream. this is intetesting and interested me a lot"):
  51. print(t.text)

image.png

简单注明
  1. Jieba的cut函数的返回结果是一个generator,所以是使用join进行链接之后才能够使用正则表达式等等的对于字符串进行处理的操作,可以考虑直接使用lcut生成一个列表
  2. 附上jieba词性表 | 词性 | 类型 | 说明 | | —- | —- | —- | | Ag | 形语素 | 形容词性语素。形容词代码为 a,语素代码g前面置以A。 | | a | 形容词 | 取英语形容词 adjective的第1个字母。 | | ad | 副形词 | 直接作状语的形容词。形容词代码 a和副词代码d并在一起。 | | an | 名形词 | 具有名词功能的形容词。形容词代码 a和名词代码n并在一起。 | | b | 区别词 | 取汉字“别”的声母。 | | c | 连词 | 取英语连词 conjunction的第1个字母。 | | dg | 副语素 | 副词性语素。副词代码为 d,语素代码g前面置以D。 | | d | 副词 | 取 adverb的第2个字母,因其第1个字母已用于形容词。 | | e | 叹词 | 取英语叹词 exclamation的第1个字母。 | | f | 方位词 | 取汉字“方” | | g | 语素 | 绝大多数语素都能作为合成词的“词根”,取汉字“根”的声母。 | | h | 前接成分 | 取英语 head的第1个字母。 | | i | 成语 | 取英语成语 idiom的第1个字母。 | | j | 简称略语 | 取汉字“简”的声母。 | | k | 后接成分 | | | l | 习用语 | 习用语尚未成为成语,有点“临时性”,取“临”的声母。 | | m | 数词 | 取英语 numeral的第3个字母,n,u已有他用。 | | Ng | 名语素 | 名词性语素。名词代码为 n,语素代码g前面置以N。 | | n | 名词 | 取英语名词 noun的第1个字母。 | | nr | 人名 | 名词代码 n和“人(ren)”的声母并在一起。 | | ns | 地名 | 名词代码 n和处所词代码s并在一起。 | | nt | 机构团体 | “团”的声母为 t,名词代码n和t并在一起。 | | nz | 其他专名 | “专”的声母的第 1个字母为z,名词代码n和z并在一起。 | | o | 拟声词 | 取英语拟声词 onomatopoeia的第1个字母。 | | p | 介词 | 取英语介词 prepositional的第1个字母。 | | q | 量词 | 取英语 quantity的第1个字母。 | | r | 代词 | 取英语代词 pronoun的第2个字母,因p已用于介词。 | | s | 处所词 | 取英语 space的第1个字母。 | | tg | 时语素 | 时间词性语素。时间词代码为 t,在语素的代码g前面置以T。 | | t | 时间词 | 取英语 time的第1个字母。 | | u | 助词 | 取英语助词 auxiliary | | vg | 动语素 | 动词性语素。动词代码为 v。在语素的代码g前面置以V。 | | v | 动词 | 取英语动词 verb的第一个字母。 | | vd | 副动词 | 直接作状语的动词。动词和副词的代码并在一起。 | | vn | 名动词 | 指具有名词功能的动词。动词和名词的代码并在一起。 | | w | 标点符号 | | | x | 非语素字 | 非语素字只是一个符号,字母 x通常用于代表未知数、符号。 | | y | 语气词 | 取汉字“语”的声母。 | | z | 状态词 | 取汉字“状”的声母的前一个字母。 | | un | 未知词 | 不可识别词及用户自定义词组。取英文Unkonwn首两个字母。(非北大标准,CSW分词中定义) |