2

假设我有一个元组格式的标记文本(单词,标签)。我想将其转换为字符串,以便对标签进行一些更改。我下面的函数只看到文本中的最后一句话,我想有一些我无法意识到的明显和愚蠢的错误,所以请帮助使其适用于整个文本。

>>> 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
4

1 回答 1

3
>>> ' '.join(' '.join(nltk.tag.tuple2str(item) for item in sent) for sent in tpl)
'This/V is/V one/NUM sentence/NN ./. And/CNJ This/V is/V another/DET one/NUM'

编辑:

如果您希望这是可逆的,那么就不要进行外部连接。

>>> [' '.join([nltk.tag.tuple2str(item) for item in sent]) for sent in tpl]
['This/V is/V one/NUM sentence/NN ./.', 'And/CNJ This/V is/V another/DET one/NUM']

编辑2:

我以为我们已经讨论过了...

>>> [[nltk.tag.str2tuple(re.sub('/NUM', '/N', w)) for w in s.split()] for s in t0]
[[('This', 'V'), ('is', 'V'), ('one', 'N'), ('sentence', 'NN'), ('.', '.')],
  [('And', 'CNJ'), ('This', 'V'), ('is', 'V'), ('another', 'DET'), ('one', 'N')]]

将其拆分为非列表理解形式:

def translate(tpl):
    result = []
    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()]
        result.append(t)
    return result
于 2010-11-27T23:36:28.137 回答