学习NLP第一课

欲先攻其事必先利其器
1、 安装nltk,使用
[python]  view plain  copy
  1. pip install nltk  

2、 在命令行下执行  

[python]  view plain  copy
  1. import nltk  
  2. nltk.download('punkt')  
一段原始文本要可以处理必须经过几个阶段,一般而言主要有
1、文本清理,清理掉一些不必要的字符,比如使用BeautifulSoup的get_text,一处非ascii字符等等
2、语句分离,一大段原生文本,处理成一系列的语句,用计算机术语而言就是将一个字符串分割成若干字符串,可以使用"."或者"。"或者nltk_tokenize预置的预处理函数,(使用方式 from nltk.tokenize import sent_tokenize)
3、标识化处理,机器所能理解的最小单位是单词,所以我们在语句分离的基础上还要进行分词操作,也就是将一个原生字符串分割成一系列有意义的单词NLP标识化处理的复杂性根据应用的不同而不同,标识器有很多,比如split,word_tokenize和regex_tokenize
4、词干提取,较为粗糙的规则处理过程,修枝剪叶,比如eating,eaten 共同的词根是eat,我在处理时,认为eating和eaten就是一个eat就ok
5、词性还原,包含了词根所有的变化,词性还原操作会根据当前上下文环境,将词根还原成当前应该表现的形式使用方式(from nltk.stem import WordNetLemmatizer)

6、停用词移除,比如无意义的the a  an 等词汇会被移除,一般停用词表示人工定制的,也有一些是根据给定语料库自动生成的nltk包含22种语言的停用词表

根据以上观点,涉及到的python代码是:

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2. import re  
  3. import requests  
  4. import operator  
  5. from bs4 import BeautifulSoup  
  6. from nltk.tokenize import sent_tokenize,wordpunct_tokenize,blankline_tokenize,word_tokenize  
  7. import nltk  
  8. import pymysql  
  9. import os  
  10.   
  11. def mysql_select():  
  12.     # 打开数据库连接  
  13.     db = pymysql.connect(host="localhost",user="root",passwd="root",db="csdn",charset="utf8")  
  14.     # 使用cursor()方法获取操作游标  
  15.     cursor = db.cursor()  
  16.     cursor.execute("SELECT * FROM `article_info` ORDER BY RAND() LIMIT 1")  
  17.     # 提交到数据库执行  
  18.     result = cursor.fetchall()  
  19.     db.close()  
  20.     return result  
  21.   
  22. str_text = mysql_select()  
  23. #文本清理,我只需要content的内容  
  24. str_text = str_text[0]  
  25. #获得content  
  26. str_text = str_text[3]  
  27. #进行文本清理,去掉html  
  28. soup = BeautifulSoup(str_text, 'lxml')  
  29. str_text = soup.get_text()  
  30. #print("文本清理的结果: "+ str_text)  
  31. #语句分离器  
  32. text_list = sent_tokenize(str_text)  
  33. #标识化处理,针对所有的语句进行标识化处理  
  34. word_list = []  
  35. #使用nltk的内置函数进行语句分离  
  36. for sentence in text_list:  
  37.     item_list = word_tokenize(sentence)  
  38.     word_list.extend(item_list)  
  39. result_1_word_list = []  
  40. for word in word_list:  
  41.     blank_list = blankline_tokenize(word)  
  42.     result_1_word_list.extend(blank_list)  
  43.     ''''' 
  44. print("查看分词结果") 
  45. for item in result_1_word_list: 
  46.     print(item) 
  47.     '''  
  48. #去掉停用詞  
  49. stop_words = [word.strip().lower() for word in ['{','}','(',')',']','[']]  
  50. clean_tokens = [tok for tok in result_1_word_list if len(tok.lower())>1 and (tok.lower not in stop_words)]  
  51. token_nltk_result = nltk.FreqDist(clean_tokens)  
  52. for k,v in token_nltk_result.items():  
  53.     print(str(k)+" : "+str(v))  
  54. token_nltk_result.plot(10,cumulative=True)  

猜你喜欢

转载自blog.csdn.net/dasgk/article/details/80091070