无法从 utils 导入 process_tweets

时间:2020-12-19 13:06:56

标签: python nlp nltk sentiment-analysis

感谢您对此进行调查,我有一个 Python 程序,我需要将 process_tweetbuild_freqs 用于某些 NLP 任务,nltk 已经安装并且 utils 不是所以我通过pip install utils安装了它,但上面提到的两个模块显然没有安装,我得到的错误是这里的标准错误,

ImportError: cannot import name 'process_tweet' from
'utils' (C:\Python\lib\site-packages\utils\__init__.py)

我做错了什么还是遗漏了什么? 我也提到了 This stackoverflow answer 但它没有帮助。

4 个答案:

答案 0 :(得分:1)

试试这个代码,它应该可以工作:
def process_tweet(tweet):
stemmer = PorterStemmer()
stopwords_english = stopwords.words('english')
tweet = re.sub(r'\$\w*', '', tweet)
tweet = re.sub(r'^RT[\s]+', '', tweet)
tweet = re.sub(r'https?:\/\/.*[\r\n]*', '', tweet)
tweet = re.sub(r'#', '', tweet)
tokenizer = TweetTokenizer(preserve_case=False,        strip_handles=True,reduce_len=True)
tweet_tokens = tokenizer.tokenize(tweet)

tweets_clean = []
for word in tweet_tokens:
    if (word not in stopwords_english and  
            word not in string.punctuation): 
        stem_word = stemmer.stem(word)  # stemming word
        tweets_clean.append(stem_word)

return tweets_clean

答案 1 :(得分:1)

您可以使用 ?? 轻松访问任何源代码,例如在本例中:process_tweet?? (以上代码来自 deeplearning.ai NLP 课程客户工具库):

def process_tweet(tweet):
"""Process tweet function.
Input:
    tweet: a string containing a tweet
Output:
    tweets_clean: a list of words containing the processed tweet

"""
stemmer = PorterStemmer()
stopwords_english = stopwords.words('english')
# remove stock market tickers like $GE
tweet = re.sub(r'\$\w*', '', tweet)
# remove old style retweet text "RT"
tweet = re.sub(r'^RT[\s]+', '', tweet)
# remove hyperlinks
tweet = re.sub(r'https?:\/\/.*[\r\n]*', '', tweet)
# remove hashtags
# only removing the hash # sign from the word
tweet = re.sub(r'#', '', tweet)
# tokenize tweets
tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True,
                           reduce_len=True)
tweet_tokens = tokenizer.tokenize(tweet)

tweets_clean = []
for word in tweet_tokens:
    if (word not in stopwords_english and  # remove stopwords
            word not in string.punctuation):  # remove punctuation
        # tweets_clean.append(word)
        stem_word = stemmer.stem(word)  # stemming word
        tweets_clean.append(stem_word)

答案 2 :(得分:0)

如果您正在学习 deeplearning.ai 上的 NLP 课程,那么我相信 utils.py 文件是由该课程的讲师创建的,用于实验室课程,不应与通常的 utils 混淆。

答案 3 :(得分:0)

我想您不需要像所有那样使用 process_tweet。课程中的代码只是总结你从开始到词干步骤所做的一切的捷径;因此,只需忽略该步骤,只需打印出 tweet_stem 即可查看原始文本和预处理文本之间的差异。