【问题标题】:nltk corpus tweeter_sample by categorynltk 语料库 tweeter_sample 按类别
【发布时间】:2017-05-10 15:43:12
【问题描述】:

我想用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'

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

【问题讨论】:

    标签: python twitter nltk sentiment-analysis


    【解决方案1】:

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

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

    因此,要将推文分类为正面或负面,只需选择相应的文件即可。这不是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 个,显然没有分类。

    【讨论】:

    • 非常感谢您的回答@alexis,但我在问题中犯了一个错误,我希望每个单词都分开。这样我就可以使用'nltk.FreqDist(documents)'
    【解决方案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]))
    

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      相关资源
      最近更新 更多