【发布时间】:2017-01-20 00:58:22
【问题描述】:
我正在练习使用 NLTK 从原始推文中删除某些功能,然后希望删除(对我而言)不相关的推文(例如空推文或单字推文)。但是,似乎某些单字推文没有被删除。我还面临无法删除句子开头或结尾的任何停用词的问题。
有什么建议吗?目前,我希望将一个句子作为输出而不是标记化的单词列表传回。
欢迎对改进代码(处理时间、优雅性)提出任何其他意见。
import string
import numpy as np
import nltk
from nltk.corpus import stopwords
cache_english_stopwords=stopwords.words('english')
cache_en_tweet_stopwords=stopwords.words('english_tweet')
# For clarity, df is a pandas dataframe with a column['text'] together with other headers.
def tweet_clean(df):
temp_df = df.copy()
# Remove hyperlinks
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('https?:\/\/.*\/\w*', '', regex=True)
# Remove hashtags
# temp_df.loc[:,"text"]=temp_df.loc[:,"text"].replace('#\w*', '', regex=True)
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('#', ' ', regex=True)
# Remove citations
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\@\w*', '', regex=True)
# Remove tickers
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\$\w*', '', regex=True)
# Remove punctuation
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[' + string.punctuation + ']+', '', regex=True)
# Remove stopwords
for tweet in temp_df.loc[:,"text"]:
tweet_tokenized=nltk.word_tokenize(tweet)
for w in tweet_tokenized:
if (w.lower() in cache_english_stopwords) | (w.lower() in cache_en_tweet_stopwords):
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[\W*\s?\n?]'+w+'[\W*\s?]', ' ', regex=True)
#print("w in stopword")
# Remove quotes
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\&*[amp]*\;|gt+', '', regex=True)
# Remove RT
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\s+rt\s+', '', regex=True)
# Remove linebreak, tab, return
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[\n\t\r]+', ' ', regex=True)
# Remove via with blank
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('via+\s', '', regex=True)
# Remove multiple whitespace
temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\s+\s+', ' ', regex=True)
# Remove single word sentence
for tweet_sw in temp_df.loc[:, "text"]:
tweet_sw_tokenized = nltk.word_tokenize(tweet_sw)
if len(tweet_sw_tokenized) <= 1:
temp_df.loc["text"] = np.nan
# Remove empty rows
temp_df.loc[(temp_df["text"] == '') | (temp_df['text'] == ' ')] = np.nan
temp_df = temp_df.dropna()
return temp_df
【问题讨论】:
-
请编辑 您的问题 以解释
df是一个熊猫数据框(我从您的 cmets 收集)。理想情况下,您应该添加几行代码,以便在有人想为您提供更好的答案时运行完整的 sn-p。如果您认为自己的自我回答已经解决了您的问题,您最终应该将其标记为“已接受”。 (但首先我会解决您的问题,并等待更好的答案)。