嗨,亲爱的,我对nltk停止词有一个问题:如果我做一个循环,停止检查字母而不是单词。我怎么能改变这种行为?举个例子:
import pandas as pd
import nltk
stopword = nltk.corpus.stopwords.words('italian')
pd.set_option('display.max_colwidth', None)
df = pd.read_csv('esempioTweet.csv', sep =',')
def remove_stop(text):
text = [word for word in text if word not in stopword]
return text
df['Testo_no_stop'] = df['Testo_token'].apply(lambda x: remove_stop(x))
df.head()考虑到前面的一篇专栏文章:
[covid, calano, i, nuovi, contagi, e, tamponi]我希望有这样的输出:
[covid, calano, nuovi, contagi, tamponi]但我的产出如下:
[v,d,n, ...]据我所知,秒针只在一个字母上运行,而不是在整个单词上,为什么?我确信我的remove_stop函数的工作方式是正确的,但是为什么秒针操作错误呢?谢谢你为我付出的耐心。
发布于 2021-12-15 12:59:30
您的代码使用for word in text,如果文本是字符串,则每次返回一个字母。
我将删除熊猫的代码简化为无关紧要--将remove_stop略为修改为使用word in text.split(),尽管我认为nltk可能有一种将文本拆分为单词的方法,例如,它可能会删除split()不会使用的标点符号。
import nltk
stopwords = nltk.corpus.stopwords.words('italian')
phrase = "oggi piove e non esco"
def remove_stop(text):
global stopwords
text = [word for word in text.split() if word not in stopwords]
return text
res = remove_stop(phrase)
print( f"{res=}" )输出:
res=['oggi', 'piove', 'esco']顺便说一句,我不认为你需要灯笼,只要用:
df['Testo_no_stop'] = df['Testo_token'].apply(remove_stop)不要忘记,您可以将调试添加到像remove_stop()这样的函数中,这是用于循环而不是不可调试的理解的一个很好的理由。
类似地,您可以打印stopwords来检查它是一个列表。它是。
https://stackoverflow.com/questions/70362716
复制相似问题