nltk 语料库 tweeter_sample 按类别

nltk corpus tweeter_sample by category

我想用 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)]

但它给了我这个错误:

    Traceback (most recent call last):
  File "C:/Users/neptun/PycharmProjects/Thesis/First_sentimental.py", line 6, in <module>
    for category in twitter_samples.categories()
  File "C:\Users\neptun\AppData\Local\Programs\Python\Python36-32\lib\site-packages\nltk\corpus\util.py", line 119, in __getattr__
    return getattr(self, attr)
AttributeError: 'TwitterCorpusReader' object has no attribute 'categories'

我不知道如何为他们提供可用属性,以便让我的列表包含正面和负面情绪。

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

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

所以要获得分类为正面或负面的推文,只需 select 相应的文件。这不是 nltk 处理分类语料库的通常方式,但你已经知道了。

documents = ([(t, "pos") for t in twitter_samples.strings("positive_tweets.json")] + 
             [(t, "neg") for t in twitter_samples.strings("negative_tweets.json")])

这将为您提供包含 10000 条推文的数据集。第三个文件包含另外 20000 个,显然没有分类。

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]))