nltk语料库tweeter_分类示例

2024-04-28 12:40:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用tweeter_sample语料库来训练nltk,但是当我试图按类别加载示例时,出现了一个错误。在

首先我试着这样做:

from nltk.corpus import twitter_samples

documents = [(list(twitter_samples.strings(fileid)), category)
             for category in twitter_samples.categories()
             for fileid in twitter_samples.fileids(category)]

但它给了我一个错误:

^{pr2}$

我不知道如何给他们可用的属性,以使我的清单有积极和消极的情绪。在


Tags: sampleinfrom示例for错误twittercorpus
2条回答
categorized_tweets = ([(t, "pos") for t in twitter_samples.strings("positive_tweets.json")] +
                            [(t, "neg") for t in twitter_samples.strings("negative_tweets.json")])


smilies = [':-)', ':)', ';)', ':o)', ':]', ':3', ':c)', ':>', '=]', '8)', '=)', ':}',
    ':^)', ':-D', ':D', '8-D', '8D', 'x-D', 'xD', 'X-D', 'XD', '=-D', '=D',
    '=-3', '=3', ':-))', ":'-)", ":')", ':*', ':^*', '>:P', ':-P', ':P', 'X-P',
    'x-p', 'xp', 'XP', ':-p', ':p', '=p', ':-b', ':b', '>:)', '>;)', '>:-)',
    '<3', ':L', ':-/', '>:/', ':S', '>:[', ':@', ':-(', ':[', ':-||', '=L', ':<',
    ':-[', ':-<', '=\\', '=/', '>:(', ':(', '>.<', ":'-(", ":'(", ':\\', ':-c',
    ':c', ':{', '>:\\', ';(', '(', ')', 'via']

categorized_tweets_tokens = []
for tweet in categorized_tweets:
    text = tweet[0]
    for smiley in smilies:
        text = re.sub(re.escape(smiley), '', text)
    categorized_tweets_tokens.append((word_tokenize(text), tweet[1]))

如果您检查twitter_samples.fileids(),您将看到有单独的正反文件:

>>> twitter_samples.fileids()
['negative_tweets.json', 'positive_tweets.json', 'tweets.20150430-223406.json']

因此,要将tweets分类为肯定或否定,只需选择相应的文件。这不是nltk处理分类语料库的常用方法,但是你已经有了它。在

^{pr2}$

这将得到10000条tweets的数据集。第三个文件包含另外20000个,显然没有分类。在

相关问题 更多 >