如何在python中从模块模式的parsetree输出转换文本对象?

2024-06-03 03:57:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个单词列表:

['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将列表中的每个组件转换为字符串,但这会更改所有输出。你知道吗


Tags: info列表np组件nn单词sentencejj
1条回答
网友
1楼 · 发布于 2024-06-03 03:57:30

从它们的documentation来看,似乎没有直接的方法或属性来获得您想要的东西。你知道吗

但是我发现Sentence对象可以使用repr打印为Sentence('urgente/JJ/B-ADJP/O/urgente')。所以我看了the source code for the ^{} implementation看看它是如何形成的:

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

似乎“括号中的”字符串是单词和标记的组合。然后您可以重用该代码,因为您知道如果您已经有了pattern.text.tree.Text对象,“文本是一个句子对象列表。每个句子都是单词对象的列表。(来自Parse trees documentation)。你知道吗

下面是我的破解方案:

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输出的所有属性/方法)。你知道吗

相关问题 更多 >