文本的信息很多,我们需要如何提取有用的信息?
比如一句话:
Json is a good boy
我们希望得到的信息是json 和 a good boy
那么首先我们需要对句子进行分词和判断单词的属性:
可以用下面的代码:
def ie_preprocess(document):
... sentences = nltk.sent_tokenize(document)
... sentences = [nltk.word_tokenize(sent) for sent in sentences]
... sentences = [nltk.pos_tag(sent) for sent in sentences]
然后需要我们规定需要提取的信息的类型:
也就是语法上的格式:
grammar = "NP: {<DT>?<JJ>*<NN>}"
这里DT是定语,JJ是形容词,NN是名词
cp = nltk.RegexpParser(grammar)
之后使用
result = cp.parse(sentence)
对语句进行分析
会得到一个nltk.tree.Tree的结构的东西
然后我们通过:
for n in chunked:
if isinstance(n, nltk.tree.Tree):
if n.node=='NP':
a = n
这样的代码拿到我们需要的片段
实际中,这个方法并不能去掉一些非英语的单词
我们可以加入:
d = enchant.Dict("en_US")
这样的判读去删选。
希望对大家有帮助。