将标记和标记转换为 Synsets

Converting Tokens and Tags to Synsets

提问人:Christie 提问时间:11/16/2023 更新时间:11/16/2023 访问量:5

问:

我正在尝试编写一个函数来将字符串转换为语法集列表。此函数应返回文档中的语法集列表,方法是首先使用 nltk.word_tokenize 标记文档,然后使用 nltk.pos_tag 查找该标记的词性。然后它应该使用 wn.synsets(token, wordnet_tag) 找到每个令牌的相应语法集。应使用第一个 synset 匹配。如果没有匹配项,则跳过该令牌。

我一直在给出一个名为“convert_tag”的函数,我无法更改:

%%capture
import numpy as np
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
nltk.download('omw-1.4')
from nltk.corpus import wordnet as wn
import pandas as pd
nltk.data.path.append("assets/")

def convert_tag(tag):
    """Convert the tag given by nltk.pos_tag to the tag used by wordnet.synsets"""
    
    tag_dict = {'N': 'n', 'J': 'a', 'R': 'r', 'V': 'v'}
    try:
        return tag_dict[tag[0]]
    except KeyError:
        return None

这是我为我的函数编写的代码:

def doc_to_synsets(doc):
    """
    Returns a list of synsets in document.

    Tokenizes and tags the words in the document doc.
    Then finds the first synset for each word/tag combination.
    If a synset is not found for that combination it is skipped.

    Args:
        doc: string to be converted

    Returns:
        list of synsets

    Example:
        doc_to_synsets('Fish are friends.')
        Out: [Synset('fish.n.01'), Synset('be.v.01'), Synset('friend.n.01')]
    """
    
    tokens = nltk.word_tokenize(doc)
    tags = nltk.pos_tag(tokens)
    wordnet_tags = [convert_tag(tag[1]) for tag in tags]
    synsets_list = []

    for tag, token in zip(wordnet_tags, tokens):
        if tag is not None:
            synset = wn.synsets(token, tag)
            if len(synset) >= 1:
                synsets_list.append(synset[0])

    return synsets_list

当我尝试文档时:“鱼是朋友。 我得到了正确的语法:[Synset('fish.n.01'), Synset('be.v.01'), Synset('friend.n.01')]。

当我尝试另一个示例文档时:“我喜欢猫。 我希望得到这些同步集:[Synset('iodine.n.01'), Synset('wish.v.02'), Synset('cat.n.01')] 但相反,我的代码没有选择“I”的标记:[Synset('wish.v.02'), Synset('cat.n.01')]

我知道我可以更改convert_tag函数以包含“PRP”和“PRP$”标签,但这不在问题描述中,并且在 juptyer notebooks autograder 中也没有给我正确的结果。

数据科学 NLTK 文本挖掘 Wordnet Synset

评论


答: 暂无答案