在Python中创建多级字典POS tagger

2024-04-27 04:30:40 发布

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

我有一个带有POS标签的文本文件。例如:

“NN狗VB跳跃…”

我需要创建一个字典,其中条目的键是单词,值是另一个字典,标签是键,标签的频率是值。所以我需要的是这样的:

{'The':{'DT':47}},{'dog':{'VB':32}}。。。你知道吗

我现在完全不知所措。首先,我将文本文件拆分为一个字符串列表,使用

'DT的' 'NN狗' 'VB跳跃'

我不确定这是不是正确的第一步。请帮帮我!你知道吗


Tags: the字符串pos目的列表字典dtnn
1条回答
网友
1楼 · 发布于 2024-04-27 04:30:40

这种方法应该为您提供所要查找的结构,POS计数是所呈现语料库中该标记的完整计数。你知道吗

注意:使用RETAIN_PUNCTUATION_FLAGRETAIN_CASE_FLAG可以切换行为,在求值前去掉标点符号,使大小写统一,或保留上/下大小写,或者两者都做。在这里,它们都被赋值为False,所有单词都将被处理为小写,所有ASCII标点符号都将在求值之前被去除。你知道吗

我添加了word_listpos_list作为备选列表。你知道吗

from string import punctuation

RETAIN_PUNCTUATION_FLAG = False
RETAIN_CASE_FLAG = False

string = "DT The NN dog VB jumps DT the NN sofa. DT The NN cat VB pages DT the NN page."

punctuation_strip_table = str.maketrans('', '', punctuation)
if RETAIN_CASE_FLAG and RETAIN_PUNCTUATION_FLAG:
    pass
elif RETAIN_CASE_FLAG and not RETAIN_PUNCTUATION_FLAG:
    string = string.translate(punctuation_strip_table)
elif not RETAIN_CASE_FLAG and RETAIN_PUNCTUATION_FLAG:
    string = string.casefold()
elif not RETAIN_CASE_FLAG and not RETAIN_PUNCTUATION_FLAG:
    string = string.casefold().translate(punctuation_strip_table)

list_all = string.split(' ')
pos_word_pairs = set(zip(
            list_all[0:][::2],
            list_all[1:][::2]))

pos_list = {pos.upper(): {
    'count': list_all.count(pos),
    'words': [
        word
        for match_pos, word in pos_word_pairs
        if match_pos == pos]
    }
    for pos in set(list_all[0:][::2])}
word_list = {word: {
    'count': list_all.count(word),
    'pos': [
        pos.upper()
        for pos, match_word in pos_word_pairs
        if match_word == word]
    }
    for word in set(list_all[1:][::2])}
paired = {
        word: {
            pos.upper():
            list_all.count(pos)}
        for pos, word
        in pos_word_pairs}

print('pos_list:', pos_list)
print()
print('word_list:', word_list)
print()
print('paired:',paired)

输出:

pos_list: {'VB': {'count': 2, 'words': ['pages', 'jumps']}, 'NN': {'count': 4, 'words': ['page', 'dog', 'sofa', 'cat']}, 'DT': {'count': 4, 'words': ['the']}}

word_list: {'dog': {'count': 1, 'pos': ['NN']}, 'cat': {'count': 1, 'pos': ['NN']}, 'jumps': {'count': 1, 'pos': ['VB']}, 'the': {'count': 4, 'pos': ['DT']}, 'page': {'count': 1, 'pos': ['NN']}, 'sofa': {'count': 1, 'pos': ['NN']}, 'pages': {'count': 1, 'pos': ['VB']}}

paired: {'pages': {'VB': 2}, 'jumps': {'VB': 2}, 'the': {'DT': 4}, 'page': {'NN': 4}, 'dog': {'NN': 4}, 'sofa': {'NN': 4}, 'cat': {'NN': 4}}

相关问题 更多 >