当前位置:   article > 正文

NLP之NLTK、spacy、jieba(中文)的使用_nltk jieba

nltk jieba

一、NLTK库的基本使用 

  1. import nltk #pip install nltk
  2. nltk.download() # 下载语言模型
  1. from nltk.tokenize import word_tokenize # 把句子转成一个一个词
  2. from nltk.text import Text
  3. input_str = "Today's weather is good, very windy and sunny, we have no classes in the afternoon,We have to play basketball tomorrow."
  4. tokens = word_tokenize(input_str)
  5. # 查看词库中前5个词
  6. tokens = [word.lower() for word in tokens]
  7. print(tokens[:5])
  1. from nltk.tokenize import word_tokenize # 把句子转成一个一个词
  2. from nltk.text import Text
  3. input_str = "Today's weather is good, very windy and sunny, we have no classes in the afternoon,We have to play basketball tomorrow."
  4. tokens = word_tokenize(input_str)
  5. t = Text(tokens) # 创建一个TEXT对象, 可以计算某一个词的个数和索引,也可以画图
  6. print(t.count('good')) # 1
  7. print(t.index('good')) # 4
  8. t.plot(8)
  1. """
  2. 停用词的使用
  3. """
  4. from nltk.corpus import stopwords
  5. print(stopwords.readme().replace('\n', ' ')) # 停用词的介绍
  6. print(stopwords.fileids()) # 各个组国家的停用词
  7. print(stopwords.raw('english').replace('\n',' ')) # 查看某个国家的停用词
  1. """
  2. 词性标注
  3. """
  4. nltk.download() # 下载第三个
  5. from nltk import pos_tag
  6. tags = pos_tag(tokens)
  7. print(tags)

 

  1. """
  2. 分块
  3. """
  4. from nltk.chunk import RegexpParser
  5. entence = [('the','DT'),('little','JJ'),('yellow','JJ'),('dog','NN'),('died','VBD')]
  6. grammer = "MY_NP: {<DT>?<JJ>*<NN>}"
  7. cp = nltk.RegexpParser(grammer) #生成规则
  8. result = cp.parse(sentence) #进行分块
  9. print(result)
  10. result.draw() #调用matplotlib库画出来

  1. import nltk
  2. nltk.download()
  3. #maxent_ne_chunke
  4. #words
  5. from nltk import ne_chunk
  6. sentence = "Edison went to Tsinghua University today."
  7. print(ne_chunk(pos_tag(word_tokenize(sentence))))

 

数据清洗示例

  1. def txt_data_clean(text):
  2. cache_english_stopwords = stopwords.words('english')
  3. # print('原始数据:', text, '\n')
  4. # 去掉HTML标签(e.g. &amp;)
  5. text_no_special_entities = re.sub(r'\&\w*;|#\w*|@\w*', '', text)
  6. # print('去掉特殊标签后的:', text_no_special_entities, '\n')
  7. # 去掉一些价值符号
  8. text_no_tickers = re.sub(r'\$\w*', '', text_no_special_entities)
  9. # print('去掉价值符号后的:', text_no_tickers, '\n')
  10. # 去掉超链接
  11. text_no_hyperlinks = re.sub(r'https?:\/\/.*\/\w*', '', text_no_tickers)
  12. # print('去掉超链接后的:', text_no_hyperlinks, '\n')
  13. # 去掉一些专门名词缩写,简单来说就是字母比较少的词
  14. text_no_small_words = re.sub(r'\b\w{1,2}\b', '', text_no_hyperlinks)
  15. # print('去掉专门名词缩写后:', text_no_small_words, '\n')
  16. # 去掉多余的空格
  17. text_no_whitespace = re.sub(r'\s\s+', ' ', text_no_small_words)
  18. text_no_whitespace = text_no_whitespace.lstrip(' ')
  19. # print('去掉空格后的:', text_no_whitespace, '\n')
  20. # 分词
  21. tokens = word_tokenize(text_no_whitespace)
  22. # print('分词结果:', tokens, '\n')
  23. # 去停用词
  24. list_no_stopwords = [i for i in tokens if i not in cache_english_stopwords]
  25. # print('去停用词后结果:', list_no_stopwords, '\n')
  26. # 过滤后结果
  27. text_filtered = ' '.join(list_no_stopwords) # ''.join() would join without spaces between words.
  28. # print('过滤后:', text_filtered)
  29. return text_filtered

二、spacy的基本使用

  1. # 导入工具包和英文模型
  2. # python -m spacy download en 用管理员身份打开CMD
  3. import spacy
  4. nlp = spacy.load('en')
  1. """
  2. 分词,分句,词性,命名实体识别
  3. """
  4. import spacy
  5. nlp = spacy.load('en')
  6. str_ = 'Weather is good, very windy and sunny. We have no classes in the afternoon.'
  7. doc = nlp(str_)
  8. print(doc) # 分词
  9. print(doc.sents) # 分句
  10. for token in doc:
  11. print ('{}-{}'.format(token,token.pos_)) # 查看每个词的词性
  12. for ent in doc.ents:
  13. print ('{}-{}'.format(ent,ent.label_)) # 命名实体识别
  14. # 命名实体识别可视化展示
  15. from spacy import displacy
  16. doc = nlp('I went to Paris where I met my old friend Jack from uni.')
  17. displacy.render(doc,style='ent',jupyter=False) # jupyter 是否在jupyternotebook上面展示
  18. from collections import Counter # 用于计数
  19. c = Counter()
  20. print(c.most_common(10)) # 查看前10个

三、jieba使用(针对的是中文)

  1. import jieba
  2. seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
  3. print("全模式: " + "/ ".join(seg_list)) # 全模式 会输出所有可能性
  4. # 全模式: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学
  5. seg_list = jieba.cut("他来到了网易杭研大厦") # 默认是精确模式
  6. print(", ".join(seg_list))
  7. # 他, 来到, 了, 网易, 杭研, 大厦
  1. """
  2. 自定义词典
  3. """
  4. import jieba
  5. jieba.load_userdict("./data/mydict.txt") #需UTF-8,可以在另存为里面设置
  6. #也可以用jieba.add_word("乾清宫")
  7. text = "故宫的著名景点包括乾清宫、太和殿和黄琉璃瓦等"
  8. # 全模式
  9. seg_list = jieba.cut(text, cut_all=True)
  10. print(u"[全模式]: ", "/ ".join(seg_list))
  11. # [全模式]: 故宫/ 的/ 著名/ 著名景点/ 景点/ 包括/ 乾清宫/ 清宫/ / / 太和/ 太和殿/ 和/ 黄琉璃瓦/ 琉璃/ 琉璃瓦/ 等
  12. # 精确模式
  13. seg_list = jieba.cut(text, cut_all=False)
  14. print(u"[精确模式]: ", "/ ".join(seg_list))
  15. # [精确模式]: 故宫/ 的/ 著名景点/ 包括/ 乾清宫/ 、/ 太和殿/ 和/ 黄琉璃瓦/ 等

3、词性标注

  1. """
  2. 关键词 抽取 越少的越稀有
  3. """
  4. import jieba.analyse
  5. import jieba
  6. seg_list = jieba.cut(text, cut_all=False)
  7. print (u"分词结果:")
  8. print ("/".join(seg_list)) # 故宫/的/著名景点/包括/乾清宫/、/太和殿/和/黄琉璃瓦/等
  9. #获取关键词
  10. tags = jieba.analyse.extract_tags(text, topK=5, withWeight=True)
  11. print (u"关键词:")
  12. print (" ".join(tags)) # 著名景点 乾清宫 黄琉璃瓦 太和殿 故宫
  13. for word, weight in tags:
  14. print(word, weight)
  15. # 著名景点 2.3167796086666668
  16. # 乾清宫 1.9924612504833332
  17. # 黄琉璃瓦 1.9924612504833332
  18. # 太和殿 1.6938346722833335
  19. # 故宫 1.5411195503033335

4、词性标注 

  1. import jieba.posseg as pseg
  2. words = pseg.cut("我爱北京天安门")
  3. for word, flag in words:
  4. print("%s %s" % (word, flag))
  5. # 我 r
  6. # 爱 v
  7. # 北京 ns
  8. # 天安门 ns

5、词云展示

  1. import jieba
  2. from wordcloud import WordCloud
  3. from scipy.misc import imread
  4. from collections import Counter
  5. import matplotlib.pyplot as plt
  6. data={}
  7. text_file = open('./data/19Congress.txt','r',encoding='utf-8')
  8. text = text_file.read()
  9. with open('./data/stopwords.txt',encoding='utf-8') as file:
  10. stopwords = {line.strip() for line in file}
  11. seg_list = jieba.cut(text, cut_all=False)
  12. for word in seg_list:
  13. if len(word)>=2:
  14. if not data.__contains__(word):
  15. data[word]=0
  16. data[word]+=1
  17. #print(data)
  18. my_wordcloud = WordCloud(
  19. background_color='white', #设置背景颜色
  20. max_words=400, #设置最大实现的字数
  21. font_path=r'./data/SimHei.ttf', #设置字体格式,如不设置显示不了中文
  22. mask=imread('./data/mapofChina.jpg'), #指定在什么图片上画
  23. width=1000,
  24. height=1000,
  25. stopwords = stopwords
  26. ).generate_from_frequencies(data)
  27. plt.figure(figsize=(18,16))
  28. plt.imshow(my_wordcloud)
  29. plt.axis('off')
  30. plt.show() # 展示词云
  31. my_wordcloud.to_file('result.jpg')
  32. text_file.close()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/497892
推荐阅读
相关标签
  

闽ICP备14008679号