- 首先需要准备一个英语停用词列表,可以使用nltk库提供的现成列表:
import nltk
nltk.download('stopwords') # 下载停用词列表
english_stopwords = nltk.corpus.stopwords.words('english') # 获取英语停用词列表
- 然后定义一个函数,接受一个推文字符串作为参数,在函数中使用split()方法把字符串分隔成单词列表,然后使用列表推导式遍历单词列表,删除英语停用词,最后使用join()方法把单词列表拼接成字符串。
def remove_stopwords(tweet):
tweet_words = tweet.split() # 分隔成单词列表
cleaned_words = [word for word in tweet_words if word.lower() not in english_stopwords] # 列表推导式删除停用词
cleaned_tweet = ' '.join(cleaned_words) # 使用join()方法拼接单词列表成字符串
return cleaned_tweet
- 测试一下函数是否能够正常工作:
tweet = "This is a tweet with some English stop words such as 'the', 'and', 'a'."
cleaned_tweet = remove_stopwords(tweet)
print(cleaned_tweet) # 输出:"tweet English stop words 'the', 'and', 'a'."