美文网首页
作业笔记10_nltk

作业笔记10_nltk

作者: ChZ_CC | 来源:发表于2017-02-07 14:09 被阅读992次

    加载nltk.book中的text,完成以下问题

    1. 在text2中有多少个词?有多少个不同的词?
    2. 尝试写一个切片表达式提取text2中最后两个词。
    3. 查找text5中的2-gram搭配,并统计搭配频数

    伯乐在线:Python自然语言处理入门

    下载安装nltk与nltk_data

    1. nltk包的安装

      • 在Mac和Unix系统上
        • 终端运行:sudo pip install -U nltk
        • 需要numpy支持
      • 在Windows系统上
        • tar包,下载地址
        • 解压,在cmd命令行进入解压好的文件夹,执行python setup.py install
      • 进入python环境,运行import nltk,没报错就行。
    2. 下载nltk_data

      • 方法1:python环境下执行以下代码:

        import nltk
        nltk.download()
        

        出现一个下载窗口,选择路径,下载需要的数据包。

        特点,很慢。我下载过无数次都没成功。

      • 方法2:手动下载nltk_data,放到python的lib中。

        • 老师给的资料试了一下,加载出错。又从新找资源。

        • 下载地址:GitHub,packages文件夹下的内容就就是nltk_data。

        • 把下好的nltk_data放到python目录下。其实用户目录也可以。看出错提醒这里,它会在这些目录下查找。

          所以放在任意一个目录下面都行,方便自己找就好了。

    3. 一个出错问题的解决过程

      在加载nltk.book的时候出错了,先看出错的代码:

      >>> from nltk.book import *
      *** Introductory Examples for the NLTK Book ***
      Loading text1, ..., text9 and sent1, ..., sent9
      Type the name of the text or sentence to view it.
      Type: 'texts()' or 'sents()' to list the materials.
      text1: Moby Dick by Herman Melville 1851
      text2: Sense and Sensibility by Jane Austen 1811
      text3: The Book of Genesis
      text4: Inaugural Address Corpus
      text5: Chat Corpus
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\book.py", line 35, in <module>
          text6 = Text(webtext.words('grail.txt'),
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\corpus\util.py", line 99, in __getattr__
          self.__load()
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\corpus\util.py", line 61, in __load
          root = nltk.data.find('corpora/%s' % self.__name)
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\data.py", line 628, in find
          return find(modified_name, paths)
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\data.py", line 614, in find
          return ZipFilePathPointer(p, zipentry)
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\compat.py", line 561, in _decorator
          return init_func(*args, **kwargs)
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\data.py", line 469, in __init__
          zipfile = OpenOnDemandZipFile(os.path.abspath(zipfile))
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\compat.py", line 561, in _decorator
          return init_func(*args, **kwargs)
        File "C:\Users\yishikeji-05\Anaconda3\lib\site-packages\nltk\data.py", line 979, in __init__
          zipfile.ZipFile.__init__(self, filename)
        File "C:\Users\yishikeji-05\Anaconda3\lib\zipfile.py", line 1026, in __init__
          self._RealGetContents()
        File "C:\Users\yishikeji-05\Anaconda3\lib\zipfile.py", line 1093, in _RealGetContents
          raise BadZipFile("File is not a zip file")
      zipfile.BadZipFile: File is not a zip file
      
      • 错误类型是BadZipFile,需要的文件不是zip格式的file。然后我就各种查啊搜啊。均无果。

      • 然后,仔细看了一下错误日志,最上面显示出错的代码行是text6 = Text(webtext.words('grail.txt')这里。

      • 所以应该是webtext这个文件的问题。于是我就去nltk_data中找webtext。果然有个叫webtext.zip的压缩包。打开里面果然有grail.txt这个文件的,那解压了试试吧。

      >>> from nltk.book import *
      *** Introductory Examples for the NLTK Book ***
      Loading text1, ..., text9 and sent1, ..., sent9
      Type the name of the text or sentence to view it.
      Type: 'texts()' or 'sents()' to list the materials.
      text1: Moby Dick by Herman Melville 1851
      text2: Sense and Sensibility by Jane Austen 1811
      text3: The Book of Genesis
      text4: Inaugural Address Corpus
      text5: Chat Corpus
      text6: Monty Python and the Holy Grail
      text7: Wall Street Journal
      text8: Personals Corpus
      text9: The Man Who Was Thursday by G . K . Chesterton 1908
      >>>
      

      呵呵哒,神奇的好了。

    可以做作业了

    上面已经加载过nltk和nltk.book了,就在命令行继续做吧。

    1. 在text2中有多少个词?有多少个不同的词?

      >>> len(text2)
      141576
      >>> len(set(text2))
      6833
      
    2. 尝试写一个切片表达式提取text2中最后两个词。

      直接当做一个list来选取最后两个项目能行吗?

      >>> text2[-2:]
      ['THE', 'END']
      
    3. 查找text5中的2-gram搭配,并统计搭配频数

      代码部分

      import nltk
      from nltk.book import text2,text5
      import re
      from collections import OrderedDict
      
      # text2的单词数,和无重复单词数
      print(len(text2),len(set(text2)))
      
      # text2的最后两个词
      print(text2[-2:])
      
      # text5中的2-gram搭配,统计搭配频数
      def getNgrams(input, n):
          output = dict()
          for i in range(len(input)-n+1):
              newNGram = " ".join(input[i:i+n])
              if newNGram in output:
                  output[newNGram] += 1
              else:
                  output[newNGram] = 1
          return output
      
      ngrams = getNgrams(text5, 2)
      print(ngrams)
      ngrams_freq = OrderedDict(sorted(ngrams.items(), key=lambda t: t[1], reverse=True))
      print(ngrams_freq)
      

      结果输出:

      2-grams结果:

      image

      词频统计结果:

      image

    相关文章

      网友评论

          本文标题:作业笔记10_nltk

          本文链接:https://www.haomeiwen.com/subject/mpapittx.html