我有一组文档,我想将它们转换为这样的形式,这样我就可以对这些文档中的单词进行 tfidf 计数(这样每个文档都由 tfidf 数字向量表示)。
我认为调用 WordNetLemmatizer.lemmatize(word) 就足够了,然后调用 PorterStemmer - 但所有 'have'、'has'、'had' 等都不会被词形还原器转换为 'have' - 并且它适用其他词也是如此。然后我读到,我应该为词形还原器提供提示 - 代表单词类型的标签 - 无论是名词、动词、形容词等。
我的问题是 - 我如何获得这些标签?我应该对这些文档执行什么操作才能得到这个?
我正在使用 python3.4,并且一次对单个单词进行词形还原 + 词干提取。我尝试了 WordNetLemmatizer、nltk 中的 EnglishStemmer 以及 Stemming.porter2 中的 Stem()。
好吧,我用谷歌搜索了更多,找到了如何获取这些标签。
第一个必须进行一些预处理,以确保该文件将被标记化(在我的例子中,它是关于删除从 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 向量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)