假设我有一个元组格式的标记文本(单词,标签)。我想将其转换为字符串,以便对标签进行一些更改。我下面的函数只看到文本中的最后一句话,我想有一些我无法意识到的明显和愚蠢的错误,所以请帮助使其适用于整个文本。
>>> import nltk
>>> tpl = [[('This', 'V'), ('is', 'V'), ('one', 'NUM'), ('sentence', 'NN'), ('.', '.')], [('And', 'CNJ'), ('This', 'V'), ('is', 'V'), ('another', 'DET'), ('one', 'NUM')]]
def translate(tuple2string):
for sent in tpl:
t = ' '.join([nltk.tag.tuple2str(item) for item in sent])
>>> print t
'And/CNJ This/V is/V another/DET one/NUM'
PS对于那些有兴趣的人,这里描述了tuple2str函数
编辑:现在我应该将它转换回具有相同格式的元组。我该怎么做?
>>> [nltk.tag.str2tuple(item) for item in t.split()]
上面的一个转换成整个元组,但我需要嵌入一个(与输入(tpl
)相同)
EDIT2:好吧,可能值得发布整个代码:
def translate(tpl):
t0 = [' '.join([nltk.tag.tuple2str(item) for item in sent]) for sent in tpl]
for t in t0:
t = re.sub(r'/NUM', '/N', t)
t = [nltk.tag.str2tuple(item) for item in t.split()]
print t