• 【深度学习】实验18 自然语言处理


    自然语言处理

    自然语言处理(Natural Language Processing, NLP)是一种计算机科学和人工智能的交叉学科,致力于使计算机能够理解、分析、生成和处理自然语言文本(如英语、中文等)。这种技术涉及到语言学、统计学、机器学习、人工智能等领域的知识和技术。

    NLP的目标是使计算机能够像人类一样理解自然语言,并与人类进行自然的交流。具体来说,NLP可以用于文本分类、信息提取、问答系统、自然语言生成、机器翻译、语音识别等方面。

    在NLP技术中,常用的方法包括词法分析、语法分析、语义分析和自然语言生成。其中,词法分析是将输入文本分解成单词、标点符号等基本元素的过程;语法分析则是确定这些基本元素之间的规则和关系;语义分析则是理解文本的含义,并从中提取出相关信息;自然语言生成是通过一些规则和模板,将计算机生成的数据转化为符合自然语言规则的文本。

    NLP的应用非常广泛。在搜索引擎中,NLP可以帮助搜索引擎优化搜索结果,并提供更准确的信息;在垃圾邮件过滤中,NLP可以检测和过滤掉垃圾邮件;在文本分类中,NLP可以将文本分为不同的类别,用于信息管理和数据分析;在机器翻译中,NLP可以将一种语言翻译成另一种语言。

    尽管NLP已经在许多领域得到了广泛应用,但它仍然面临着许多挑战。其中最大的挑战之一是语言的多义性。由于自然语言的歧义性很高,NLP系统必须具备高度的智能才能正确地解释文本的意义。此外,不同语言之间的差异以及不同人之间的不同表达方式也给NLP技术带来了一定的挑战。

    总的来说,NLP是非常有前途的技术,其可以帮助人们更好地理解和处理自然语言文本,并在许多领域发挥重要作用。通过不断的改进和创新,NLP将会在未来的科技发展中扮演越来越重要的角色。

    分词技术

    1. 正向最大匹配算法

    # -*- coding: utf-8 -*-
    # MM
    # 使用正向最大匹配算法实现中文分词
    dic = []
    MAX_LENGTH = 5
     
    def init():
        """
        读文件
        获取中文词典
        :return:
        """
        input = open("test.txt")
        lines = input.readlines()
        for line in lines:
            temp = line.split(',')
            dic.append(temp[0])
        for d in dic:
            print(d)
    
    def if_contain(words):
        """
        判断当前词在词典中是否存在
        :param words:
        :return:
        """
        flag = False
        for d in dic:
            if d == words:
                flag = True
                break
        return flag
    
    def spl(sentence):
        """
        正向最大匹配算法的主要实现部分
        从后向前切割字符串,直到切割出的子串与词典中的词匹配
        :param sentence:
        :return:
        """
        result = ''
        words = []
     
        while len(sentence) > 0:
            except_flag = False
            for i in range(MAX_LENGTH, 0, -1):
                temp = sentence[:i]    # 中文字符串切割方式
                print(i,temp)
                flag = if_contain(temp)
                if flag:
                    words.append(temp)
                    sentence = sentence[i:]
                    except_flag = True
                    break
            if not except_flag:
                # 判断当前字符串是否在词典中并不存在,若该字符串从头切割到尾都没有词典中的词则认为无法切割并且
                # 词典中不存在,此时直接将该词当成切割后的结果加入结果列表
                words.append(sentence)
                break
        for w in words:
            result += (w + '/')
        return result
    
    def main():
        """
        与用户交互接口
        :return:
        """
        init()
        while True:
            input_str = input(">")
            if not input_str:
                break
            result = spl(input_str)
            print("分词结果为:")
            print(result)
     
     
    if __name__ == "__main__":
        main()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    研究
    研究生
    生命
    命
    的
    起源
    研究生命的起源
    
    5 研究生命的
    4 研究生命
    3 研究生
    5 命的起源
    4 命的起源
    3 命的起
    2 命的
    1 命
    5 的起源
    4 的起源
    3 的起源
    2 的起
    1 的
    5 起源
    分词结果为:
    研究生/命/的/起源/
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2. HanLP常用方法

    from pyhanlp import *
    
    print(HanLP.segment('你好,欢迎在Python中调用HanLP的API'))
    
    • 1
    • 2
    • 3
    [你好/vl, ,/w, 欢迎/v, 在/p, Python/nx, 中/f, 调用/v, HanLP/nx, 的/ude1, API/nx]
    
    • 1
    for term in HanLP.segment('下雨天地面积水'):
        print('{}\t{}'.format(term.word, term.nature)) # 获取单词与词性
    testCases = [
        "商品和服务",
        "结婚的和尚未结婚的确实在干扰分词啊",
        "买水果然后来世博园最后去世博会",
        "中国的首都是北京",
        "欢迎新老师生前来就餐",
        "工信处女干事每月经过下属科室都要亲口交代24口交换机等技术性器件的安装工作",
        "随着页游兴起到现在的页游繁盛,依赖于存档进行逻辑判断的设计减少了,但这块也不能完全忽略掉。"]
    for sentence in testCases: print(HanLP.segment(sentence))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    下雨天	n
    地面	n
    积水	n
    [商品/n, 和/cc, 服务/vn]
    [结婚/vi, 的/ude1, 和/cc, 尚未/d, 结婚/vi, 的/ude1, 确实/ad, 在/p, 干扰/vn, 分词/n, 啊/y]
    [买/v, 水果/n, 然后/c, 来/vf, 世博园/n, 最后/f, 去/vf, 世博会/n]
    [中国/ns, 的/ude1, 首都/n, 是/vshi, 北京/ns]
    [欢迎/v, 新/a, 老/a, 师生/n, 前来/vi, 就餐/vi]
    [工信处/n, 女干事/n, 每月/t, 经过/p, 下属/v, 科室/n, 都/d, 要/v, 亲口/d, 交代/v, 24/m, 口/n, 交换机/n, 等/udeng, 技术性/n, 器件/n, 的/ude1, 安装/v, 工作/vn]
    [随着/p, 页游/nz, 兴起/v, 到/v, 现在/t, 的/ude1, 页游/nz, 繁盛/a, ,/w, 依赖于/v, 存档/vi, 进行/vn, 逻辑/n, 判断/v, 的/ude1, 设计/vn, 减少/v, 了/ule, ,/w, 但/c, 这/rzv, 块/q, 也/d, 不能/v, 完全/ad, 忽略/v, 掉/v, 。/w]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    # 关键词提取
    document = "水利部水资源司司长陈明忠9月29日在国务院新闻办举行的新闻发布会上透露," \
               "根据刚刚完成了水资源管理制度的考核,有部分省接近了红线的指标," \
               "有部分省超过红线的指标。对一些超过红线的地方,陈明忠表示,对一些取用水项目进行区域的限批," \
               "严格地进行水资源论证和取水许可的批准。"
    print(HanLP.extractKeyword(document, 2))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
       [水资源, 陈明忠]
    
    • 1
    # 自动摘要
    print(HanLP.extractSummary(document, 3))
    
    • 1
    • 2
       [严格地进行水资源论证和取水许可的批准, 水利部水资源司司长陈明忠9月29日在国务院新闻办举行的新闻发布会上透露, 有部分省超过红线的指标]
    
    • 1
    # 依存句法分析
    print(HanLP.parseDependency("徐先生还具体帮助他确定了把画雄鹰、松鼠和麻雀作为主攻目标。"))
    
    • 1
    • 2
    1	徐先生	徐先生	nh	nr	_	4	主谓关系	_	_
    2	还	还	d	d	_	4	状中结构	_	_
    3	具体	具体	a	ad	_	4	状中结构	_	_
    4	帮助	帮助	v	v	_	0	核心关系	_	_
    5	他	他	r	r	_	4	兼语	_	_
    6	确定	确定	v	v	_	4	动宾关系	_	_
    7	了	了	u	u	_	6	右附加关系	_	_
    8	把	把	p	p	_	15	状中结构	_	_
    9	画	画	v	v	_	8	介宾关系	_	_
    10	雄鹰	雄鹰	n	n	_	9	动宾关系	_	_
    11	、	、	wp	w	_	12	标点符号	_	_
    12	松鼠	松鼠	n	n	_	10	并列关系	_	_
    13	和	和	c	c	_	14	左附加关系	_	_
    14	麻雀	麻雀	n	n	_	10	并列关系	_	_
    15	作为	作为	v	v	_	6	动宾关系	_	_
    16	主攻	主攻	v	vn	_	17	定中关系	_	_
    17	目标	目标	n	n	_	15	动宾关系	_	_
    18	。	。	wp	w	_	4	标点符号	_	_
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3. Jieba常用方法

    # encoding=utf-8
    import jieba
    # 全模式
    seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
    print("Full Mode: " + "/ ".join(seg_list)) 
    print(seg_list)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    Building prefix dict from the default dictionary ...
    Loading model from cache /tmp/jieba.cache
    Loading model cost 0.743 seconds.
    Prefix dict has been built successfully.
    Full Mode: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    # 精确模式
    seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
    print("Default Mode: " + "/ ".join(seg_list))  
    
    • 1
    • 2
    • 3
    Default Mode: 我/ 来到/ 北京/ 清华大学
    
    • 1
    # 默认是精确模式
    seg_list = jieba.cut("他来到了网易杭研大厦")  
    print(", ".join(seg_list))
    
    • 1
    • 2
    • 3
    他, 来到, 了, 网易, 杭研, 大厦
    
    • 1
    # 搜索引擎模式
    seg_list = jieba.cut_for_search("我来到北京清华大学")  
    print("/".join(seg_list))
    
    • 1
    • 2
    • 3
    我/来到/北京/清华/华大/大学/清华大学
    
    • 1
    seg_list = jieba.lcut("我来到北京清华大学", cut_all=True)
    print(seg_list)
    
    • 1
    • 2
    ['我', '来到', '北京', '清华', '清华大学', '华大', '大学']
    
    • 1
    # encoding=utf-8
    text1 = '李小福是创新办主任也是云计算方面的专家'
    seg_list1 = jieba.cut(text1, cut_all=False)
    print("/ ".join(seg_list1))
    
    • 1
    • 2
    • 3
    • 4
    李小福/ 是/ 创新/ 办/ 主任/ 也/ 是/ 云/ 计算/ 方面/ 的/ 专家
    
    • 1
    # 自定义词典
    text1 = '李小福是创新办主任也是云计算方面的专家'
    # 'userdict.txt'为自定义词典的路径
    jieba.load_userdict('userdict.txt') 
    seg_list1 = jieba.cut(text1, cut_all=False)
    print("/ ".join(seg_list1))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    李小福/ 是/ 创新办/ 主任/ 也/ 是/ 云计算/ 方面/ 的/ 专家
    
    • 1

    构建词向量

    1. 基于sklearn构建One-hot词向量

    from numpy import array
    from numpy import argmax
    from sklearn.preprocessing import LabelEncoder
    from sklearn.preprocessing import OneHotEncoder
    from warnings import filterwarnings
    filterwarnings('ignore')
    # define example
    data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm', 'hot']
    values = array(data)
    print(values)
    # integer encode
    label_encoder = LabelEncoder()
    integer_encoded = label_encoder.fit_transform(values)
    print(integer_encoded)
    # binary encode
    onehot_encoder = OneHotEncoder(sparse=False)
    integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
    onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
    print(onehot_encoded)
    # invert first example
    inverted = label_encoder.inverse_transform([argmax(onehot_encoded[0, :])])
    print(inverted)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    ['cold' 'cold' 'warm' 'cold' 'hot' 'hot' 'warm' 'cold' 'warm' 'hot']
    [0 0 2 0 1 1 2 0 2 1]
    [[1. 0. 0.]
     [1. 0. 0.]
     [0. 0. 1.]
     [1. 0. 0.]
     [0. 1. 0.]
     [0. 1. 0.]
     [0. 0. 1.]
     [1. 0. 0.]
     [0. 0. 1.]
     [0. 1. 0.]]
    ['cold']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2. 基于gensim构建word2vec词向量

    # -*- coding: utf-8 -*-
     
    import jieba
    import jieba.analyse
     
    jieba.suggest_freq('沙瑞金', True)
    jieba.suggest_freq('田国富', True)
    jieba.suggest_freq('高育良', True)
    jieba.suggest_freq('侯亮平', True)
    jieba.suggest_freq('钟小艾', True)
    jieba.suggest_freq('陈岩石', True)
    jieba.suggest_freq('欧阳菁', True)
    jieba.suggest_freq('易学习', True)
    jieba.suggest_freq('王大路', True)
    jieba.suggest_freq('蔡成功', True)
    jieba.suggest_freq('孙连城', True)
    jieba.suggest_freq('季昌明', True)
    jieba.suggest_freq('丁义珍', True)
    jieba.suggest_freq('郑西坡', True)
    jieba.suggest_freq('赵东来', True)
    jieba.suggest_freq('高小琴', True)
    jieba.suggest_freq('赵瑞龙', True)
    jieba.suggest_freq('林华华', True)
    jieba.suggest_freq('陆亦可', True)
    jieba.suggest_freq('刘新建', True)
    jieba.suggest_freq('刘庆祝', True)
     
    with open('./in_the_name_of_people.txt') as f:
        document = f.read()
        
        #document_decode = document.decode('GBK')
        
        document_cut = jieba.cut(document)
        #print  ' '.join(jieba_cut)  //如果打印结果,则分词效果消失,后面的result无法显示
        result = ' '.join(document_cut)
        result = result.encode('utf-8')
        with open('./in_the_name_of_people_segment.txt', 'wb') as f2:
            f2.write(result)
    f.close()
    f2.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    Building prefix dict from the default dictionary ...
    Dumping model to file cache /tmp/jieba.cache
    Loading model cost 1.790 seconds.
    Prefix dict has been built successfully.
    
    • 1
    • 2
    • 3
    • 4
    # import modules & set up logging
    import logging
    import os
    from gensim.models import word2vec
     
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
     
    sentences = word2vec.LineSentence('./in_the_name_of_people_segment.txt') 
     
    model = word2vec.Word2Vec(sentences, hs=1,min_count=1,window=3) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    #沙书记最相近的一些3个字的词(主要是人名)如下:
    #gensim.models.Word2Vec.similar_by_wordword [,topn,restrict_vocab]):找到前N个最相似的单词。
    req_count = 5
    for key in model.wv.similar_by_word('沙瑞金'.encode('utf-8').decode('utf-8'), topn =100):
        if len(key[0])==3:
            req_count -= 1
            print(key[0], key[1])
            if req_count == 0:
                break;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    高育良 0.9653146862983704
    田国富 0.953415036201477
    侯亮平 0.9278725385665894
    李达康 0.9275027513504028
    易学习 0.9119865298271179
    
    • 1
    • 2
    • 3
    • 4
    • 5
    #看两个词向量的相近程度
    #gensim.models.Word2Vec.similarity(ws1,ws2):计算两个单词之间的余弦相似度。
    print(model.wv.similarity('沙瑞金'.encode('utf-8').decode('utf-8'), '钟小艾'.encode('utf-8').decode('utf-8')))
    print(model.wv.similarity('沙瑞金'.encode('utf-8').decode('utf-8'), '李达康'.encode('utf-8').decode('utf-8')))
    
    • 1
    • 2
    • 3
    • 4
    0.85246694
    0.9275029
    
    • 1
    • 2
    #找出不同类的词
    print(model.wv.doesnt_match(u"沙瑞金 高育良 李达康 钟小艾".split()))
    
    • 1
    • 2
    钟小艾
    
    • 1

    附:系列文章

    序号文章目录直达链接
    1波士顿房价预测https://want595.blog.csdn.net/article/details/132181950
    2鸢尾花数据集分析https://want595.blog.csdn.net/article/details/132182057
    3特征处理https://want595.blog.csdn.net/article/details/132182165
    4交叉验证https://want595.blog.csdn.net/article/details/132182238
    5构造神经网络示例https://want595.blog.csdn.net/article/details/132182341
    6使用TensorFlow完成线性回归https://want595.blog.csdn.net/article/details/132182417
    7使用TensorFlow完成逻辑回归https://want595.blog.csdn.net/article/details/132182496
    8TensorBoard案例https://want595.blog.csdn.net/article/details/132182584
    9使用Keras完成线性回归https://want595.blog.csdn.net/article/details/132182723
    10使用Keras完成逻辑回归https://want595.blog.csdn.net/article/details/132182795
    11使用Keras预训练模型完成猫狗识别https://want595.blog.csdn.net/article/details/132243928
    12使用PyTorch训练模型https://want595.blog.csdn.net/article/details/132243989
    13使用Dropout抑制过拟合https://want595.blog.csdn.net/article/details/132244111
    14使用CNN完成MNIST手写体识别(TensorFlow)https://want595.blog.csdn.net/article/details/132244499
    15使用CNN完成MNIST手写体识别(Keras)https://want595.blog.csdn.net/article/details/132244552
    16使用CNN完成MNIST手写体识别(PyTorch)https://want595.blog.csdn.net/article/details/132244641
    17使用GAN生成手写数字样本https://want595.blog.csdn.net/article/details/132244764
    18自然语言处理https://want595.blog.csdn.net/article/details/132276591
  • 相关阅读:
    java实现html转pdf(node+puppeteer)
    电脑重装系统Win10关闭网速限制的方法
    Hexagon_V65_Programmers_Reference_Manual(48)
    系列四、FileReader和FileWriter
    一文拿捏线程和线程池的创建方式
    Jenkins设置root权限(13)
    Opencv项目实战:04 全景图片拼接
    VSCode工具使用
    HIVESQL的列转行和行转列使用总结
    ubuntu同步本地代码到github最新版
  • 原文地址:https://blog.csdn.net/m0_68111267/article/details/133408205