如何在 NLTK 中创建用于情感分析的语料库?

How to create a corpus for sentiment analysis in NLTK?

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

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

"on a Mac it would be in ~/nltk_data/corpora, for instance. And it looks like you also have to append your new corpus to the __init__.py within .../site-packages/nltk/corpus/."

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

如果需要,我可以 post 我尝试使用 "PlaintextCorpusReader" 以及下面提供的追溯进行编码,尽管我宁愿完全不必使用 PlaintextCorpusReader 来无缝使用,而宁愿只是对 .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'

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

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 中,或破解 nltk.corpus.__init__.py 以像本地语料库一样加载它。事实上,不要做这些事情。

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

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

如果您向文件夹中添加新文件,reader 将找到并使用它们。如果您想要的是能够将您的脚本与其他文件夹一起使用,那么就这样做吧——您不需要不同的 reader,您需要了解 sys.argv。如果您正在寻找 pos.txtneg.txt 的分类语料库,那么您需要一个 CategorizedPlaintextCorpusReader(请参阅)。如果您还想要其他东西,请编辑您的问题 来解释您想要做什么。