处理嵌入的元组/字符串,python
假设我有一个带标签的文本,格式是(单词,标签)的元组。我想把它转换成字符串,以便对标签进行一些修改。下面我的函数只看到了文本的最后一句,我觉得这里肯定有一些明显而愚蠢的错误,我自己没意识到,所以请帮我让它能处理整个文本。
>>> 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'
附注:对于那些感兴趣的人,tuple2str函数的描述可以在这里找到。
编辑:现在我应该把它转换回元组,保持相同的格式。我该怎么做呢?
>>> [nltk.tag.str2tuple(item) for item in t.split()]
上面的代码将整个元组转换了,但我需要的是嵌套的元组(和输入的格式(tpl
)一样)。
编辑2:好吧,可能值得发布整个代码:
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
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