如何使用 conllu 库创建 TokenList?

How to create a TokenList using the conllu library?

我正在尝试使用 conllu 库创建一个 CoNLL-U 文件,作为我正在处理的通用依赖性标记项目的一部分。

我在 python 列表中有很多句子。这些包含标记、引理、词性标签、特征等的子列表。例如:

sentence = [['The', 'the', 'DET', ... ], ['big', big', 'ADJ', ... ], ['dog', 'dog', 'NOUN', ...], ...]

我想把这些变成CoNLL-U解析语句的过程自动化,所以我写了下面的函数:

from collections import OrderedDict

def compile_sent(sent):
    sent_list = list()
    for i, tok_data in enumerate(sent):
        tok_id = i + 1
        tok = tok_data[0]
        lemma = tok_data[1]
        pos = tok_data[2]
        feats = tok_data[3]
        compiled_tok = OrderedDict({'id': tok_id, 'form': tok, 'lemma': lemma, 'upostag': pos, 'xpostag': None, 'feats': feats, 'head': None, 'deprel': None, 'deps': None, 'misc': None})
        sent_list.append(compiled_tok)
    sent_list = sent_list.serialize()
    return sent_list

print(compile_sent(sentence))

当我尝试 运行 此代码时,出现以下错误:

Traceback (most recent call last):
  File "/Users/me/PycharmProjects/UDParser/Rough_Work.py", line 103, in <module>
    print(compile_sent(sentence))
  File "/Users/me/PycharmProjects/UDParser/Rough_Work.py", line 99, in compile_sent
    sent_list = sent_list.serialize()
AttributeError: 'list' object has no attribute 'serialize'

问题是我正在尝试创建一个普通列表,运行 serialize() 方法就在上面。当 parse() 函数在 CoNLL-U 文件格式的字符串上 运行 时,我不知道如何创建由库创建的 TokenList 类型。

当您尝试打印该类型的列表时,您会得到以下输出:

data = """
# text = The big dog
1   The     the    DET    _    Definite=Def|PronType=Art   _   _   _   _
2   big     big    ADJ    _    Degree=Pos                  _   _   _   _
3   dog     dog    NOUN   _    Number=Sing                 _   _   _   _

"""

sentences = data.parse()
sentence = sentences[0]
print(sentence)

TokenList<The, quick, brown, fox, jumps, over, the, lazy, dog, .>

运行 此类列表上的 serialize() 方法会将其转回 CoNLL-U 格式字符串,如上例中的 data 。但是,当您尝试在普通 python 列表中 运行 它时,它会中断。

如何创建这样的 TokenList 而不是普通的 python 列表对象?

将您的 sent_list 从普通列表更改为 TokenList

from conllu import TokenList
from collections import OrderedDict

def compile_sent(sent):
    sent_list = TokenList()
    # ... etc ...

您可以在 REPL 中使用 help(TokenList) 查看 TokenList 上的函数。