#!/usr/bin/env python
# coding: utf-8
·上下文無關文法cfg
# in[7]:
get_ipython(
).run_line_magic(
'pinfo2'
,'nltk.cfg.fromstring'
)# in[3]:
import nltk
grammar1 = nltk.cfg.fromstring(
''' s -> np vp
vp -> v np | v np pp
pp -> p np
v -> 'saw' | 'ate' |'walked'
np -> 'john' | 'mary' | 'bob' | det n | det n pp
det -> 'a' | 'an' | 'the' | 'my'
n -> 'man' | 'dog' | 'cat' | 'telescope' | 'park'
p -> 'in' | 'on' | 'by' | 'with'
''')
# in[5]:
sent =
'mary saw bob'
.split(
)rd_parser = nltk.recursivedescentparser(grammar1)
for tree in rd_parser.parse(sent)
:print
(tree)
# in[ ]:
·結構上有歧義:一句話符合多個文法規則!!!如:介詞短語附著歧義
# in[13]:
grammer1 = nltk.data.load(r'file:c:/users/xue/desktop/nlp/mygrammar.cfg'
)# in[20]:
sent =
'mary saw bob'
.split(
)rd_parser = nltk.recursivedescentparser(grammar1, trace=2)
# 開啟跟蹤設定!
for tree in rd_parser.parse(sent)
:print
(tree)
# in[21]:
for p in grammar1.productions():
print
(p)
·直接遞迴
·間接遞迴
# in[31]:
grammar = nltk.cfg.fromstring(
''' s -> np vp
np -> det nom | propn
nom -> adj nom | n
vp -> v adj | v np | v s | v np pp
pp -> p np
propn -> 'buster' | 'chatterer' |'joe'
det -> 'a' | 'an' | 'the' | 'my'
n -> 'bear' | 'dog' | 'cat' | 'telescope' | 'park' | 'tree' | 'fish' | 'log' | 'squirrel'
adj -> 'angry' | 'frightened' | 'little' | 'tall'
v -> 'chased' | 'saw' | 'said' | 'thought' | 'was' | 'put'
p -> 'on'
''')
# in[29]:
sent =
'the angry bear chased the frightened little squirrel'
.split(
)rd_parser = nltk.recursivedescentparser(grammar)
# 開啟跟蹤設定!
for tree in rd_parser.parse(sent)
:print
(tree.draw())
# in[32]:
sent =
'chatterer said buster thought the tree was tall'
.split(
)rd_parser = nltk.recursivedescentparser(grammar)
for tree in rd_parser.parse(sent)
: tree.draw(
)
語言處理與Python 8 1一些語法困境
前面章節的簡單總結 前面的學習中,主要焦點在與 詞彙。如何識別,分析詞彙的結構 分配詞彙類別 以及獲得詞彙的含義。還有如何識別詞彙序列或者n gram的模式。8.1一些語法困境 語言資料和無限可能性 每天都在增加電子語言,資料量是非常大的 句子的組合具有無線的可能性 普遍存在的歧義 讓我們仔細看看短...
81 程序的一些方法
from multiprocessing import process,current process import time import os 每個程序都會有自己的id號pid deftask print 子程序 當前程序的id號 print current process pid print ...
R一些語法
1.讀檔案 讀csv檔案 u read.csv g jd data data jdata user.csv header true 不加header預設false,即就是資料框的列名為v1,v2.header true,第一列為列名2.隨機抽樣 sample x,size,replace false...