1. 程式人生 > >《使用Python進行自然語言處理(Nltk)》2

《使用Python進行自然語言處理(Nltk)》2

import nltk
from nltk.corpus import *

'''1、古騰堡語料庫'''
gutenberg.fileids()       #所有古騰堡語料庫中的文字
emma = nltk.corpus.gutenberg.words('austen-emma.txt')
#num_chars 變數計數了空白字元
#row()對檔案的內容不進行任何語言處理
#sents()函式把文字劃分成句子,其中每一個句子是一個詞連結串列


'''非正規文字語料庫'''
from nltk.corpus import webtext
for fileid in webtext.fileids():
    print fileid

'''即時訊息聊天會話語料庫'''
from nltk.corpus import nps_chat
chatroom =nps_chat.posts('10-19-20s_706posts.xml')
chatroom[123]

'''2、布朗語料庫
布朗語料庫是第一個百萬詞級的英語電子語料庫的,
由布朗大學於 1961 年建立。這個語料庫包含 500 個不同來源的文字,
按照文體分類,如:新聞、社論等。'''


'''3、路透社語料庫
路透社語料庫包含 10,788 個新聞文件,共計 130 萬字。這些文件分成 90 個主題,
按照“訓練”和“測試”分為兩組。與布朗語料庫不同,路透社語料庫的類別是有互相重疊的,
只是因為新聞報道往往涉及多個主題。我們可以查詢由一個或多個文件涵蓋的主題,
也可以查詢包含在一個或多個類別中的文件。
'''


'''4、就職演說語料庫
實際上是 55 個文字的集合,每個文字都是一個總統的演說。這個集合的一個有趣特性是它的時間維度。'''

'''5標註文字語料庫
NLTK 包含多國語言語料庫。“世界人權宣言” (udhr )語料庫中不同語言版本中的字長差異。
NLTK 語料庫閱讀器支援高效的訪問大量語料庫,並且能用於處理新的語料庫。NLTK 中定義的基本語料庫函式。'''

'''6 載入你自己的語料庫
(1) 將變數corpus_root的值設定為自己的語料的資料夾目錄

(2) PlaintextCorpusReader 初始化函式的第二個引數可以是需要載入的檔案,可以使用正則表示式

(3) CropsBPCRTest匯入txt一類的資料很順利,但是BracketParseCorpusReader載入賓州樹庫的實驗是失敗的,
我看了自己的賓州樹庫語料庫與書中描述的不一致但是不應該啊,還沒有找到原因,先留下這個懸案,待日後再審。'''

 測試程式碼2.0

#!/usr/python/bin
# Filename:NltkTest59,一些關於語料庫使用的測試
import nltk
from nltk.corpus import brown
from nltk.corpus import reuters
from nltk.corpus import inaugural
from nltk.corpus import udhr
from nltk.corpus import BracketParseCorpusReader
from nltk.corpus import PlaintextCorpusReader

class NltkTest59:
    def __init__(self):
        print 'Initing...'

    def BrownTest(self, genres, modals):
        '''來源於p59,對於不同問題的常用詞統計的測試'''
        cfd = nltk.ConditionalFreqDist( \
            (genre, word) \
            for genre in brown.categories() \
            for word in brown.words(categories=genre))
        cfd.tabulate(conditions=genres, samples=modals)

    def ReutersTest(self):
        # reuters.fileids()
        # reuters.categories()
        print reuters.categories('training/9865')
        print reuters.categories(['training/9865', 'training/9880'])
        # reuters.fileids('barley')
        # reuters.fileids(['barley', 'corn'])
        print reuters.words('training/9865')[:14]
        print reuters.words(['training/9865', 'training/9880'])
        print reuters.words(categories='barley')
        print reuters.words(categories=['barley', 'corn'])

    def InauguralTest(self):
        '''執行會出錯 '''
        cfd = nltk.ConditionalFreqDist( \
            (target, file[:4]) \
            for fileids in inaugural.fileids() \
            for w in inaugural.words(fileids) \
            for target in ['america', 'citizen'] \
            if w.lower().startswith(target))
        cfd.plot()

    def UdhrTest(self):
        languages = ['Chickasaw', 'English', 'German_Deutsch', \
                     'Greenlandic_Inuktikut', 'Hungarian_Magyar', 'Ibibio_Efik']
        cfd = nltk.ConditionalFreqDist( \
            (lang, len(word)) \
            for lang in languages \
            for word in udhr.words(lang + '-Latin1'))
        cfd.plot(cumulative=False)

    def CropsPCRTest(self):
        corpus_root = r'C:\corpora\udhr2'
        file_pattern = r'.*'
        encoding = 'utf-8'
        pcr = PlaintextCorpusReader(corpus_root, file_pattern)
        print pcr.fileids()
        print pcr.words('007.txt')

    def CropsBPCRTest(self):
        '''可恥的失敗了,沒法執行,可能是語料庫版本問題,或者其他,待查'''
        corpus_root = r'C:\corpora\penntreebank\parsed'
        file_pattern = r'*.wsj'
        ptb = BracketParseCorpusReader(corpus_root, file_pattern)
        print ptb.fileids()
        print len(ptb.sents())
        ptb.sents(fileids='\wsj_0001.mrg')[19]

nt59 = NltkTest59()
genres = ['news', 'religion', 'hobbies', 'science_fiction', 'romance', 'humor']
modals = ['can', 'could', 'may', 'might', 'must', 'will']
# nt59.BrownTest(genres,modals)
# nt59.ReutersTest()
# 不能執行,因為存在SOAP版本錯誤,不急著解決,以後再補一個解決方案
# nt59.InauguralTest()
nt59.UdhrTest()
# nt59.CropsPCRTest()
# nt59.CropsBPCRTest()