python-如何从python模块Pattern的parsetree输出转换为Text对象?

时间:2019-06-04 22:53:06

标签: python python-3.7 python-pattern

我有一个这样的单词列表:

['Urgente', 'Recibimos', 'Info']

我使用了parsetree (parsetree(x, lemmata = True)函数来转换单词,每个单词的输出是这样的:

[[Sentence('urgente/JJ/B-ADJP/O/urgente')],
[Sentence('recibimos/NN/B-NP/O/recibimos')],
[Sentence('info/NN/B-NP/O/info')]]

列表的每个组件的类型为pattern.text.tree.Text

我只需要将括号中的一组单词获取,但是我不知道该怎么做,我需要以下输出:

[urgente/JJ/B-ADJP/O/urgente,
recibimos/NN/B-NP/O/recibimos,
info/NN/B-NP/O/info]

我使用str将列表中的每个组件转换为字符串,但这会更改所有输出。

1 个答案:

答案 0 :(得分:0)

在他们的documentation中,似乎没有直接的方法或属性来获得想要的东西。

但是我发现可以使用SentenceSentence('urgente/JJ/B-ADJP/O/urgente')对象打印为repr。因此,我查看了the source code for the __repr__ implementation以了解其形成方式:

def __repr__(self):
    return "Sentence(%s)" % repr(" ".join(["/".join(word.tags) for word in self.words]))

似乎字符串“在括号中”是单词和标签的组合。然后,您可以重复使用该代码,知道如果您已有pattern.text.tree.Text对象,则“ 文本是Sentence对象的列表。每个Sentence是Word对象的列表。”(来自Parse trees documentation

这是我的hacky解决方案:

parsed = list()
for data in ['Urgente', 'Recibimos', 'Info']:
    parsed.append(parsetree(data, lemmata=True))

output = list()
for text in parsed:
    for sentence in text:
        formatted = " ".join(["/".join(word.tags) for word in sentence.words])
        output.append(str(formatted))

print(output)

打印output给出:

['Urgente/NNP/B-NP/O/urgente', 'Recibimos/NNP/B-NP/O/recibimos', 'Info/NNP/B-NP/O/info']

请注意,此解决方案会产生str的列表(丢失了原始parsetree输出的所有属性/方法)。