学习NLP第一课

阅读 125

2023-04-03


欲先攻其事必先利其器
1、 安装nltk,使用

    pip install nltk


    2、 在命令行下执行  


    import nltk  
    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代码是:


    # -*- coding: utf-8 -*-  
    import re  
    import requests  
    import operator  
    from bs4 import BeautifulSoup  
    from nltk.tokenize import sent_tokenize,wordpunct_tokenize,blankline_tokenize,word_tokenize  
    import nltk  
    import pymysql  
    import os  
      
    def mysql_select():  
    # 打开数据库连接  
    "localhost",user="root",passwd="root",db="csdn",charset="utf8")  
    # 使用cursor()方法获取操作游标  
        cursor = db.cursor()  
    "SELECT * FROM `article_info` ORDER BY RAND() LIMIT 1")  
    # 提交到数据库执行  
        result = cursor.fetchall()  
        db.close()  
    return result  
      
    str_text = mysql_select()  
    #文本清理,我只需要content的内容  
    str_text = str_text[0]  
    #获得content  
    str_text = str_text[3]  
    #进行文本清理,去掉html  
    soup = BeautifulSoup(str_text, 'lxml')  
    str_text = soup.get_text()  
    #print("文本清理的结果: "+ str_text)  
    #语句分离器  
    text_list = sent_tokenize(str_text)  
    #标识化处理,针对所有的语句进行标识化处理  
    word_list = []  
    #使用nltk的内置函数进行语句分离  
    for sentence in text_list:  
        item_list = word_tokenize(sentence)  
        word_list.extend(item_list)  
    result_1_word_list = []  
    for word in word_list:  
        blank_list = blankline_tokenize(word)  
        result_1_word_list.extend(blank_list)  
    '''''
    print("查看分词结果")
    for item in result_1_word_list:
        print(item)
        '''  
    #去掉停用詞  
    stop_words = [word.strip().lower() for word in ['{','}','(',')',']','[']]  
    clean_tokens = [tok for tok in result_1_word_list if len(tok.lower())>1 and (tok.lower not in stop_words)]  
    token_nltk_result = nltk.FreqDist(clean_tokens)  
    for k,v in token_nltk_result.items():  
    print(str(k)+" : "+str(v))  
    token_nltk_result.plot(10,cumulative=True)


    精彩评论(0)

    0 0 举报