【问题标题】:How to create a corpus for sentiment analysis in NLTK? [duplicate]如何在 NLTK 中创建用于情感分析的语料库? [复制]
【发布时间】:2017-03-09 07:14:58
【问题描述】:

我希望在 Visual Studio Code for MacOSX 中使用我自己创建的语料库;我可能已经阅读了一百个论坛,但我无法理解我做错了什么,因为我对编程很陌生。

This question 似乎是我能找到的最接近我需要做的事情;但是,我不知道如何执行以下操作:

“例如,在 Mac 上,它将位于 ~/nltk_data/corpora 中。看起来您还必须将新语料库附加到 .../site-packages/nltk/corpus/ 内的 __init__.py 。”

回答时,请注意我正在使用 Homebrew,如果我需要在同一编码中使用库存 NLTK 语料库数据集,我不想永久禁用其他路径。

如果需要,我可以使用“PlaintextCorpusReader”以及下面提供的回溯发布我的编码尝试,尽管我宁愿完全不必使用 PlaintextCorpusReader 进行无缝使用,而是只使用简单的复制+粘贴 for . txt 文件按照附加编码放入我希望使用的适当位置。

谢谢。

Traceback (most recent call last):
  File "/Users/jordanXXX/Documents/NLP/bettertrainingdata", line 42, in <module>
    short_pos = open("short_reviews/pos.txt", "r").read
IOError: [Errno 2] No such file or directory: 'short_reviews/pos.txt'


编辑:


感谢您的回复。

我听取了您的建议,将文件夹从 NLTK 的语料库中移出。

我一直在对我的文件夹位置进行一些试验,并且得到了不同的回溯。

如果您说最好的方法是使用 PlaintextCorpusReader,那就这样吧;但是,也许对于我的应用程序,我想使用 CategorizedPlaintextCorpusReader?

sys.argv 绝对不是我的意思,所以我可以稍后再读。

首先,这是我的代码,我没有尝试使用 PlaintextCorpusReader,当包含 pos.txt 和 neg.txt 文件的文件夹“short_reviews”位于 NLP 文件夹之外时,这会导致上述回溯:

import nltk
import random
from nltk.corpus import movie_reviews
from nltk.classify.scikitlearn import SklearnClassifier
import pickle

from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC

from nltk.classify import ClassifierI
from statistics import mode

from nltk import word_tokenize

class VoteClassifier(ClassifierI):
    def __init__(self, *classifiers):
        self._classifiers = classifiers

    def classify(self, features):
        votes = []
        for c in self._classifiers:
            v = c.classify(features)
            votes.append(v)
        return mode(votes)

    def confidence(self, features):
        votes = []
        for c in self._classifiers:
            v = c.classify(features)
            votes.append(v)

        choice_votes = votes.count(mode(votes))
        conf = choice_votes / len(votes)
        return conf

# def main():
#     file = open("short_reviews/pos.txt", "r")
#     short_pos = file.readlines()
#     file.close

short_pos = open("short_reviews/pos.txt", "r").read
short_neg = open("short_reviews/neg.txt", "r").read

documents = []

for r in short_pos.split('\n'):
    documents.append( (r, "pos") )

for r in short_neg.split('\n'):
    documents.append((r, "neg"))

all_words = []

short_pos_words = word.tokenize(short_pos)
short_neg_words = word.tokenize(short_neg)

for w in short_pos_words:
    all_words.append(w. lower())

for w in short_neg_words:
    all_words.append(w. lower())

all_words = nltk.FreqDist(all_words)

但是,当我使用与上述相同但不使用 PlaintextCorpusReader 的代码将包含文本文件的文件夹“short_reviews”移动到 NLP 文件夹中时,会发生以下情况:

Traceback (most recent call last):
  File "/Users/jordanXXX/Documents/NLP/bettertrainingdata", line 47, in <module>
    for r in short_pos.split('\n'):
AttributeError: 'builtin_function_or_method' object has no attribute 'split'

当我使用下面的代码并使用 PlaintextCorpusReader 将包含文本文件的文件夹“short_reviews”移动到 NLP 文件夹中时,会发生以下 Traceback:

import nltk
import random
from nltk.corpus import movie_reviews
from nltk.classify.scikitlearn import SklearnClassifier
import pickle

from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC

from nltk.classify import ClassifierI
from statistics import mode

from nltk import word_tokenize

from nltk.corpus import PlaintextCorpusReader
corpus_root = 'short_reviews'
word_lists = PlaintextCorpusReader(corpus_root, '*')
wordlists.fileids()


class VoteClassifier(ClassifierI):
    def __init__(self, *classifiers):
        self._classifiers = classifiers

    def classify(self, features):
        votes = []
        for c in self._classifiers:
            v = c.classify(features)
            votes.append(v)
        return mode(votes)

    def confidence(self, features):
        votes = []
        for c in self._classifiers:
            v = c.classify(features)
            votes.append(v)

        choice_votes = votes.count(mode(votes))
        conf = choice_votes / len(votes)
        return conf

# def main():
#     file = open("short_reviews/pos.txt", "r")
#     short_pos = file.readlines()
#     file.close

short_pos = open("short_reviews/pos.txt", "r").read
short_neg = open("short_reviews/neg.txt", "r").read

documents = []

for r in short_pos.split('\n'):
    documents.append((r, "pos"))

for r in short_neg.split('\n'):
    documents.append((r, "neg"))

all_words = []

short_pos_words = word.tokenize(short_pos)
short_neg_words = word.tokenize(short_neg)

for w in short_pos_words:
    all_words.append(w. lower())

for w in short_neg_words:
    all_words.append(w. lower())

all_words = nltk.FreqDist(all_words)


Traceback (most recent call last):
  File "/Users/jordanXXX/Documents/NLP/bettertrainingdata2", line 18, in <module>
    word_lists = PlaintextCorpusReader(corpus_root, '*')
  File "/Library/Python/2.7/site-packages/nltk/corpus/reader/plaintext.py", line 62, in __init__
    CorpusReader.__init__(self, root, fileids, encoding)
  File "/Library/Python/2.7/site-packages/nltk/corpus/reader/api.py", line 87, in __init__
    fileids = find_corpus_fileids(root, fileids)
  File "/Library/Python/2.7/site-packages/nltk/corpus/reader/util.py", line 763, in find_corpus_fileids
    if re.match(regexp, prefix+fileid)]
  File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 141, in match
    return _compile(pattern, flags).match(string)
  File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
error: nothing to repeat

【问题讨论】:

  • 请贴出您实现错误的代码,以便对后人有所帮助。
  • 实际上有一个巧妙的技巧可以将nltk.data.findLazyCorpusReader 结合使用,这将使您的语料库看起来像是NLTK 原生的。周末有空我会上传答案。
  • 拜托,这样做。我认为学习 PlaintextCorpusReader 的功能仍然是有益的
  • 至于PlaintextCorpusReader,这里有答案:stackoverflow.com/a/20922201/610569
  • 不要打扰LazyCorpusReader。如果您遇到编码错误,则您的代码已经在查找并打开您的文件。显然,您的新问题是某些文件不是 ascii。一定要谷歌并在网站上四处寻找解决方案,因为你的新问题肯定是重复的。

标签: python nlp nltk sentiment-analysis corpus


【解决方案1】:

您提到的答案包含一些非常糟糕(或者更确切地说,不适用)的建议。没有理由将您自己的语料库放在nltk_data 中,或者破解nltk.corpus.__init__.py 以像本地语料库一样加载它。事实上,不要做这些事情。

您应该使用PlaintextCorpusReader。我不明白你不愿意这样做,但如果你的文件是纯文本,那么它是正确的工具。假设您有一个文件夹 NLP/bettertrainingdata,您可以构建一个阅读器,它将加载此文件夹中的所有 .txt 文件,如下所示:

myreader = nltk.corpus.reader.PlaintextCorpusReader(r"NLP/bettertrainingdata", r".*\.txt")

如果您将新文件添加到文件夹中,读者将找到并使用它们。如果您想要的是能够将您的脚本与其他文件夹一起使用,那么就这样做——您不需要其他阅读器,您需要了解sys.argv。如果您使用pos.txtneg.txt 进行分类语料库,那么您需要CategorizedPlaintextCorpusReader(请参阅)。如果您还需要其他内容,请编辑您的问题以解释您要做什么。

【讨论】:

  • 谢谢你,我很确定这与我找到的 alvas 链接一起工作,但如果没有像你这样的简单解释,我不确定如何应用。
猜你喜欢
  • 1970-01-01
  • 2017-11-15
  • 2011-05-15
  • 2014-01-16
  • 2017-03-09
  • 2016-03-17
  • 1970-01-01
相关资源
最近更新 更多