为什么PortStemmer在NLTK我的 “字符串” 转换为U “串”

问题描述:

import nltk 
import string 
from nltk.corpus import stopwords 


from collections import Counter 

def get_tokens(): 
    with open('comet_interest.xml','r') as bookmark: 
     text=bookmark.read() 
     lowers=text.lower() 

     no_punctuation=lowers.translate(None,string.punctuation) 
     tokens=nltk.word_tokenize(no_punctuation) 
     return tokens 
#remove stopwords 
tokens=get_tokens() 
filtered = [w for w in tokens if not w in stopwords.words('english')] 
count = Counter(filtered) 
print count.most_common(10) 

#stemming 
from nltk.stem.porter import * 

def stem_tokens(tokens, stemmer): 
    stemmed = [] 
    for item in tokens: 
     stemmed.append(stemmer.stem(item)) 
    return stemmed 

stemmer = PorterStemmer() 
stemmed = stem_tokens(filtered, stemmer) 
count = Counter(stemmed) 
print count.most_common(10) 

结果表明这样的:为什么PortStemmer在NLTK我的 “字符串” 转换为U “串”

[( '分析',13),( '空间',11),(” (''''''),(''''''),(''''''),(''''''), ,(u'spatial',11),(u'use',11),(u'feb',11),(u'spatial',11), 8),(u'cdata',8),(u'scienc',7),(u'descript',7),(u'item',6),(u'includ',6) 'mani',6)]

seco有什么问题找出一个词,为什么每个词都有一个“你”的头?

+1

...因为它们是Unicode字符串? – kindall 2015-02-12 04:20:42

+0

哦。但为什么第一个不是Unicode?以及如何从Unicode转换为字符串? – 2015-02-12 16:49:56

正如@kindall指出的那样,它是因为unicode字符串。

但更具体地讲,这是因为NLTK使用from __future__ import unicode_literals它转换ALL字符串默认为Unicode,看到https://github.com/nltk/nltk/blob/develop/nltk/stem/porter.py#L87

所以让我们尝试在Python 2.x的一个实验:

$ python 
>>> from nltk.stem import PorterStemmer 
>>> porter = PorterStemmer() 
>>> word = "analysis" 
>>> word 
'analysis' 
>>> porter.stem(word) 
u'analysi' 

我们看到突然间,这个词语变成了一个unicode。

然后,让我们尝试导入unicode_literals

>>> from nltk.stem import PorterStemmer 
>>> porter = PorterStemmer() 
>>> word = "analysis" 
>>> word 
'analysis' 
>>> porter.stem(word) 
u'analysi' 
>>> from __future__ import print_function, unicode_literals 
>>> word 
'analysis' 
>>> word2 = "analysis" 
>>> word2 
u'analysis' 

注意,所有字符串仍然为字符串,但是任何字符串变量,这是进口unicode_literals会默认成为统一后的新。

+0

这对您的其他应用程序或您使用词干结果的任何地方意味着什么? – gorjanz 2017-02-15 10:30:26