如何为nltk lemmatizer提供(或生成)标记

2024-09-28 01:33:22 发布

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

我有一组文档,我想把它们转换成这样的形式,这样我就可以计算这些文档中的tfidf单词(这样每个文档都由tfidf数字的向量表示)。在

我以为打电话就够了WordNetElemMatizer.lemmatize(单词),然后是PorterStemmer——但是所有的‘have’、‘has’、‘had’等并没有被lemmatizer转换成‘have’——它也适用于其他单词。然后我读到了,我应该为词组标记提供一个提示-标记代表一个词的类型-不管它是名词、动词、形容词等等

我的问题是-我如何得到这些标签?为了得到这些文件我该怎么做?在

我使用的是python3.4,我一次只处理一个单词的词干。我尝试了WordNetLemmatizer和nltk的EnglishStemmer以及stem()源堵塞.porter2. 在


Tags: 文档标记have数字单词向量形式tfidf
1条回答
网友
1楼 · 发布于 2024-09-28 01:33:22

好吧,我在谷歌上搜索了更多,找到了如何得到这些标签。 第一个必须做一些预处理,以确保文件将被标记化(在我的例子中,它是关于删除从pdf到txt转换后留下的一些东西)。在

然后这些文件必须被标记成句子,然后每个句子都变成单词数组,并且可以由nltk标记器标记。这样就可以完成柠檬化,然后在上面添加词干。在

from nltk.tokenize import sent_tokenize, word_tokenize
# use sent_tokenize to split text into sentences, and word_tokenize to
# to split sentences into words
from nltk.tag import pos_tag
# use this to generate array of tuples (word, tag)
# it can be then translated into wordnet tag as in
# [this response][1]. 
from nltk.stem.wordnet import WordNetLemmatizer
from stemming.porter2 import stem

# code from response mentioned above
def get_wordnet_pos(treebank_tag):
    if treebank_tag.startswith('J'):
        return wordnet.ADJ
    elif treebank_tag.startswith('V'):
        return wordnet.VERB
    elif treebank_tag.startswith('N'):
        return wordnet.NOUN
    elif treebank_tag.startswith('R'):
        return wordnet.ADV
    else:
        return ''    


with open(myInput, 'r') as f:
    data = f.read()
    sentences = sent_tokenize(data)
    ignoreTypes = ['TO', 'CD', '.', 'LS', ''] # my choice
    lmtzr = WordNetLemmatizer()
    for sent in sentences:
        words = word_tokenize(sentence)
        tags = pos_tag(words)
        for (word, type) in tags:
            if type in ignoreTypes:
                continue
            tag = get_wordnet_pos(type)
            if tag == '':
                continue
            lema = lmtzr.lemmatize(word, tag)
            stemW = stem(lema)

在这一点上,我得到了词干为stemW的词干,然后我可以将其写入文件,并使用它们来计算每个文档的tfidf向量。在

相关问题 更多 >

    热门问题