首页 > 解决方案 > 在列表中转换 conllu 文件

问题描述

我正在用python做一个项目。我必须读取一个 COLLLU 文件(我成功地完成了),但我无法转换为我希望的格式。

在一个列表中,我必须存储另一个列表,其中包含一个句子,其中每个单词都包含在一个带有 UPOS(通用语音部分)的元组中。

这是我想获得的格式:

[[('Pierre', 'NOUN'), ('Vinken', 'NOUN'), (',', '.'), ('61', 'NUM'), ('years', 'NOUN'), ('old', 'ADJ'), (',', '.'), ('will', 'VERB'), ('join', 'VERB'), ('the', 'DET'), ('board', 'NOUN'), ('as', 'ADP'), ('a', 'DET'), ('nonexecutive', 'ADJ'), ('director', 'NOUN'), ('Nov.', 'NOUN'), ('29', 'NUM'), ('.', '.')], [('Mr.', 'NOUN'), ('Vinken', 'NOUN'), ('is', 'VERB'), ('chairman', 'NOUN'), ('of', 'ADP'), ('Elsevier', 'NOUN'), ('N.V.', 'NOUN'), (',', '.'), ('the', 'DET'), ('Dutch', 'NOUN'), ('publishing', 'VERB'), ('group', 'NOUN'), ('.', '.')]]

相反,这就是我得到的

[('Pierre', 'NOUN'), ('Vinken', 'NOUN'), (',', '.'), ('61', 'NUM'), ('years', 'NOUN'), ('old', 'ADJ'), (',', '.'), ('will', 'VERB'), ('join', 'VERB'), ('the', 'DET'), ('board', 'NOUN'), ('as', 'ADP'), ('a', 'DET'), ('nonexecutive', 'ADJ'), ('director', 'NOUN'), ('Nov.', 'NOUN'), ('29', 'NUM'), ('.', '.'), ('Mr.', 'NOUN'), ('Vinken', 'NOUN'), ('is', 'VERB'), ('chairman', 'NOUN'), ('of', 'ADP'), ('Elsevier', 'NOUN'), ('N.V.', 'NOUN'), (',', '.'), ('the', 'DET'), ('Dutch', 'NOUN'), ('publishing', 'VERB'), ('group', 'NOUN'), ('.', '.')]

这是我写的代码

import pyconll
import pprint

word_tag_list = list()

conll_words_file = pyconll.load_from_file("./grc_perseus-ud-train.conllu")

for sentence in conll_words_file:
    for text in sentence:
        for word in sentence:
            word_tag_list.append(tuple((word.form, word.upos)))
print(word_tag_list)

正如您在第一个示例中注意到的那样,我为每个句子存储了一个列表,该列表包含在另一个列表中。

这是CONLLU文件的存储库:CONLLU REPOSITORY

标签: pythonpython-3.xlisttuples

解决方案


显然你想把每个句子放在它自己的子列表中。

您需要在循环内创建每个子列表,而不是将所有内容直接附加到外部列表。

word_tag_list = list()

conll_words_file = pyconll.load_from_file("./grc_perseus-ud-train.conllu")

for sentence in conll_words_file:
    sentence_list = []
    for text in sentence:
        for word in sentence:
            sentence_list.append(tuple((word.form, word.upos)))
    word_tag_list.append(sentence_list)

print(word_tag_list)

推荐阅读