嗨,我正试图从基于最后一个例子的文本字符串中提取关系:https://web.archive.org/web/20120907184244/http://nltk.googlecode.com/svn/trunk/doc /howto/relextract.html
从诸如"出版商周刊的迈克尔詹姆斯编辑"这样的字符串中,我想要的结果是输出如下:
[PER:'Michael James']','[ORG:'Publishers Weekly']的编辑
这样做的最佳方法是什么?extract_rels期望什么格式以及如何格式化输入以满足该要求?
试图自己做,但它没有奏效.这是我从本书中改编的代码.我没有打印任何结果.我究竟做错了什么?
class doc():
pass
doc.headline = ['this is expected by nltk.sem.extract_rels but not used in this script']
def findrelations(text):
roles = """
(.*(
analyst|
editor|
librarian).*)|
researcher|
spokes(wo)?man|
writer|
,\sof\sthe?\s* # "X, of (the) Y"
"""
ROLES = re.compile(roles, re.VERBOSE)
tokenizedsentences = nltk.sent_tokenize(text)
for sentence in tokenizedsentences:
taggedwords = nltk.pos_tag(nltk.word_tokenize(sentence))
doc.text = nltk.batch_ne_chunk(taggedwords)
print doc.text
for rel in relextract.extract_rels('PER', 'ORG', doc, corpus='ieer', pattern=ROLES):
print relextract.show_raw_rtuple(rel) # doctest: +ELLIPSIS
Run Code Online (Sandbox Code Playgroud)
text ="出版商周刊的Michael James编辑"
findrelations(文本)
小智 4
这是基于您的代码(只需进行一些调整),效果很好;)
import nltk
import re
from nltk.chunk import ne_chunk_sents
from nltk.sem import relextract
def findrelations(text):
roles = """
(.*(
analyst|
editor|
librarian).*)|
researcher|
spokes(wo)?man|
writer|
,\sof\sthe?\s* # "X, of (the) Y"
"""
ROLES = re.compile(roles, re.VERBOSE)
sentences = nltk.sent_tokenize(text)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences)
for doc in chunked_sentences:
print doc
for rel in relextract.extract_rels('PER', 'ORG', doc, corpus='ace', pattern=ROLES):
#it is a tree, so you need to work on it to output what you want
print relextract.show_raw_rtuple(rel)
findrelations('Michael James editor of Publishers Weekly')
Run Code Online (Sandbox Code Playgroud)
(S(迈克尔人/NNP)(詹姆斯人/NNP)编辑/NN of/IN(ORGANIZATION Publishers/NNS Weekly/NNP))
归档时间: |
|
查看次数: |
3137 次 |
最近记录: |