我正在尝试使用Python和NLTK对平均长度仅为10-20个单词的文本字符串进行文本分类。
我想要计算词频和大小为2-4的ngram,并以某种方式将它们转换为向量,并使用它们来构建SVN模型。
我在想,可能有一种非常标准的NLTK方法来做所有这些事情,但我很难找到它。
我在想,标准的方法可能已经很聪明了,比如对单词进行词干处理(因此“重要的”和“重要的”将被视为同一个单词),去掉标点符号,超级常见的英语单词,并可能实现一种聪明的方法,为我将这些计数转化为向量。我是文本分类和python的新手,我对这两种建议都持开放态度!
发布于 2018-04-01 18:08:04
好的,我第一次尝试回答堆栈溢出问题……
你的问题有点含糊,所以我会尽我所能回答。听起来像是在问如何在构建SVN模型之前准备文本,特别是如何区分文本输入、计算词频以及从给定的字符串创建n-gram。
import nltk
from collections import Counter
from nltk import ngrams
from nltk.stem import WordNetLemmatizer
# lowercase, remove punctuation, and lemmatize string
def word_generator(str):
wnl = WordNetLemmatizer()
clean = nltk.word_tokenize(str)
words = [wnl.lemmatize(word.lower()) for word in clean if word.isalpha()]
for word in words:
yield word
# create list of freqs
def freq_count(str):
voc_freq = Counter()
for word in word_generator(str):
voc_freq[word] += 1
trimmed = sorted(voc_freq.items(), reverse=True, key=lambda x: x[1])
return trimmed
# create n-grams
def make_ngrams(str, n):
grams = ngrams([word for word in word_generator(str)], n)
return list(grams)示例4-gram输出:
>>> my_str = 'This is this string, not A great Strings not the greatest string'
>>> print(freq_count(my_str))
[('string', 3), ('this', 2), ('not', 2), ('is', 1), ('a', 1), ('great', 1), ('the', 1), ('greatest', 1)]
>>> print(make_ngrams(my_str, 4))
[('this', 'is', 'this', 'string'), ('is', 'this', 'string', 'not'), ('this', 'string', 'not', 'a'), ('string', 'not', 'a', 'great'), ('not', 'a', 'great', 'string'), ('a', 'great', 'string', 'not'), ('great', 'string', 'not', 'the'), ('string', 'not', 'the', 'greatest'), ('not', 'the', 'greatest', 'string')]然后你可以用它做任何你想做的事情,比如创建向量。
https://stackoverflow.com/questions/49593080
复制相似问题