我是Python文本处理的新手,我试图在文本文档中使用词干,大约有5000行。
我写了以下脚本
from nltk.corpus import stopwords # Import the stop word list
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer('english')
def Description_to_words(raw_Description ):
# 1. Remove HTML
Description_text = BeautifulSoup(raw_Description).get_text()
# 2. Remove non-letters
letters_only = re.sub("[^a-zA-Z]", " ", Description_text)
# 3. Convert to lower case, split into individual words
words = letters_only.lower().split()
stops = set(stopwords.words("english"))
# 5. Remove stop words
meaningful_words = [w for w in words if not w in stops]
# 5. stem words
words = ([stemmer.stem(w) for w in words])
# 6. Join the words back into one string separated by space,
# and return the result.
return( " ".join( meaningful_words ))
clean_Description = Description_to_words(train["Description"][15])
但是当我测试结果时,单词没有被阻止,任何人都可以帮助我知道什么是问题,我在“Description_to_words”函数中做错了什么
而且,当我像下面一样单独执行stem命令时,它可以工作。
from nltk.tokenize import sent_tokenize, word_tokenize
>>> words = word_tokenize("MOBILE APP - Unable to add reading")
>>>
>>> for w in words:
... print(stemmer.stem(w))
...
mobil
app
-
unabl
to
add
read
答案 0 :(得分:3)
这是你的功能的每一步,都已修复。
删除HTML。
Description_text = BeautifulSoup(raw_Description).get_text()
删除非字母,但暂时不删除空格。你也可以简化一下你的正则表达式。
letters_only = re.sub("[^\w\s]", " ", Description_text)
转换为小写,分成单个单词:我建议再次使用word_tokenize
。
from nltk.tokenize import word_tokenize
words = word_tokenize(letters_only.lower())
删除停用词。
stops = set(stopwords.words("english"))
meaningful_words = [w for w in words if not w in stops]
词干。这是另一个问题。词干meaningful_words
,而非words
。
return ' '.join(stemmer.stem(w) for w in meaningful_words])