【问题标题】:How to create a TokenList using the conllu library?如何使用 conllu 库创建 TokenList?
【发布时间】:2020-05-08 00:28:41
【问题描述】:

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

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

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 列表对象?

【问题讨论】:

    标签: python nlp conll universal-pos-tag


    【解决方案1】:

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

    from conllu import TokenList
    from collections import OrderedDict
    
    def compile_sent(sent):
        sent_list = TokenList()
        # ... etc ...
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多