前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何预先处理电影评论数据以进行情感分析

如何预先处理电影评论数据以进行情感分析

作者头像
丰泽
发布2018-02-23 15:51:11
2K0
发布2018-02-23 15:51:11

对于不同的问题,文本数据的预先处理是不同的。

处理工作从简单的几步开始,例如加载数据。但是由于对您正在研究的数据的特定清理任务,这种预处理很快变得困难起来。在从何处开始,按什么顺序执行将原始数据转化成建模数据的步骤这种问题上,您需要帮助。

在本教程中,您将逐步了解如何为情感分析预先处理电影评论的文本数据。

完成本教程后,您将知道:

  • 如何加载文本数据并清除其中的标点符号和其他非文字内容。
  • 如何开发词汇表,定制词汇表,并将其保存到文件中。
  • 如何使用预先定义的词汇表和清理文本的技巧来预处理电影评论,并将其保存到可供建模的新文件中。

让我们开始吧。

  • 2017年10月更新:修正了当跳过不匹配文件时出现的小bug,谢谢Jan Zett。
  • 更新2017年12月:修正了一个示例中的小错字,感谢Ray和Zain。

如何准备电影评论数据进行情感分析
如何准备电影评论数据进行情感分析

如何预先处理电影评论数据以进行情感分析 照片由Kenneth Lu提供,保留某些权利。

教程概览

本教程分为5个部分; 他们是:

  1. 电影评论数据集
  2. 加载文本数据
  3. 清理文本数据
  4. 开发词汇表
  5. 保存预处理好的数据

需要有关文本数据深度学习的帮助?

这是我7天的临时邮箱(附带实例代码)

点击登陆,同时得到一份该教程的PDF文本

https://machinelearningmastery.lpages.co/leadbox/144855173f72a2%3A164f8be4f346dc/5655638436741120/

1.电影评论数据集

“电影评论数据”是由彭博和李莉莲于21世纪初从imdb.com网站上收集的电影评论。这些评论被收集并作为自然语言处理研究的一部分提供。

评论最初是在2002年发布的,但2004年发布了一个更新和清理后的版本,即“ v2.0 ”。

该数据集由IMDB拥有的rec.arts.movi​​es.reviews新闻组档案中的1,000个正面和1,000个负面评论组成。作者将这个数据集称为“ 极性数据集 ”。

我们的数据包含1000个正面评论和1000个负面评论,均在2002年以前编写完成。大约每个类别下,每个作者平均有20篇评论(共312位作者)。我们将这个语料库称为极性数据集。

- 情感教育:基于最小分割的主观性总结的情感分析,2004。

数据已经被一定程度上清理了,例如:

  • 数据集仅包含英文评论。
  • 所有的文本都被转换成了小写。
  • 标点符号(例如句号,逗号,括号等)周围都有空格
  • 文本每行被分成一个句子。

这些数据已被用于一些相关的自然语言处理任务。对于分类任务,经典模型(如支持向量机)的数据性能在70%到80%(例如78%到82%)的范围内。

通过10倍交叉验证,更复杂的数据预处理可能会得到高达86%的结果。如果我们希望在现代方法的实验中使用这个数据集,那么我们就需要知道一个80年代中期的概念。

... ...取决于下游极性分类器的选择,我们可以实现显著的,高度统计意义上的改善(从82.8%至86.4%)

- 情感教育:基于最小分割的主观性总结的情感分析,2004。

你可以从这里下载数据集:

解压文件后,你将会得到一个名为“ txt_sentoken ”的目录,其中有两个子目录,分别是负面和正面评论。目录名为“ neg ”和“ pos ”。每条正面和负面评论都分别存储在一个文件里,文件命名约定为 cv000cv999

接下来,让我们看看如何加载文本数据。

2.加载文本数据

在本节中,我们将着眼于先加载单个文本文件,然后处理文件的目录。

我们假定评论数据被下载到当前的工作目录“txt_sentoken"中

我们可以通过打开它,读取ASCII文本并关闭文件来加载单个文本文件。这是标准的文件处理流程。例如,我们可以加载第一个负面评论文件“ cv000_29416.txt ”,如下所示:

代码语言:js
复制
# load one file
filename = 'txt_sentoken/neg/cv000_29416.txt'
# open the file as read only
file = open(filename, 'r')
# read all text
text = file.read()
# close the file
file.close()

这将文档加载为ASCII并保留任何空白,如新行。

我们可以把它变成一个名为load_doc()的函数,它接受文档的文件名来加载并返回文本。

代码语言:js
复制
# load one file
filename = 'txt_sentoken/neg/cv000_29416.txt'
# open the file as read only
file = open(filename, 'r')
# read all text
text = file.read()
# close the file
file.close()

我们有两个目录,每个目录有1000个文件。我们可以依次处理每个目录,首先使用listdir()函数获取目录中的文件列表,然后依次加载每个文件。

例如,实际上我们可以使用load_doc()函数来加载负面评论目录中的每个文档。

代码语言:js
复制
from os import listdi
 
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# specify directory to load
directory = 'txt_sentoken/neg'
# walk through all files in the folde
for filename in listdir(directory):
    # skip files that do not have the right extension
    if not filename.endswith(".txt"):
        continue
    # create the full path of the file to open
    path = directory + '/' + filename
    # load document
    doc = load_doc(path)
    print('Loaded %s' % filename)

运行此示例,打印每个加载后评论的文件名。

代码语言:js
复制
...
Loaded cv995_23113.txt
Loaded cv996_12447.txt
Loaded cv997_5152.txt
Loaded cv998_15691.txt
Loaded cv999_14636.txt

我们可以将文档的处理做成一个函数,稍后将其用作模板来开发一个函数来清理文件夹中的所有文档。例如,下面我们定义一个process_docs()函数来做同样的事情。

代码语言:js
复制
from os import listdi
 
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# load all docs in a directory
def process_docs(directory):
    # walk through all files in the folde
    for filename in listdir(directory):
        # skip files that do not have the right extension
        if not filename.endswith(".txt"):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load document
        doc = load_doc(path)
        print('Loaded %s' % filename)
 
# specify directory to load
directory = 'txt_sentoken/neg'
process_docs(directory)

现在我们知道如何加载电影评论文本数据,让我们看看如何清理它。

3.清理文本数据

在本节中,我们将看看我们可能想要对哪些电影评论数据进行数据清理。

我们将假设我们使用一个词袋模型或者一个嵌入的词,所以不需要太多的预处理。

拆分为标符

首先,我们加载一个文件,看看由空格分割的原始标符。我们将使用前一节中开发的load_doc()函数。我们可以使用split()函数将加载的文档分割成由空格分隔的标符。

代码语言:js
复制
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# load the document
filename = 'txt_sentoken/neg/cv000_29416.txt'
text = load_doc(filename)
# split into tokens by white space
tokens = text.split()
print(tokens)

运行这个例子.就得到了一个来自文档的,很好的原始标符的长列表。

代码语言:js
复制
 'years', 'ago', 'and', 'has', 'been', 'sitting', 'on', 'the', 'shelves', 'ever', 'since', '.', 'whatever', '.', '.', '.', 'skip', 'it', '!', "where's", 'joblo', 'coming', 'from', '?', 'a', 'nightmare', 'of', 'elm', 'street', '3', '(', '7/10', ')', '-', 'blair', 'witch', '2', '(', '7/10', ')', '-', 'the', 'crow', '(', '9/10', ')', '-', 'the', 'crow', ':', 'salvation', '(', '4/10', ')', '-', 'lost', 'highway', '(', '10/10', ')', '-', 'memento', '(', '10/10', ')', '-', 'the', 'others', '(', '9/10', ')', '-', 'stir', 'of', 'echoes', '(', '8/10', ')']

只要看一下这些原始标符,我们就能得到很多可以尝试的想法,比如:

  • 从单词中删除标点符号(例如,“what's”)。
  • 删除仅仅是标点符号的标符(例如' - ')。
  • 删除包含数字的标符(例如'10 / 10')。
  • 删除只有一个字符的标符(例如'a')。
  • 删除没有太多意义的标符(例如'and')

一些想法:

  • 我们可以使用字符串translate()函数从标符中过滤掉标点符号。
  • 我们可以通过在每个标符上使用isalpha()函数来检查和移除标点符号或包含数字的标符。
  • 我们可以利用NLTK加载列表来删除英文停用词。
  • 我们可以通过检查标符的长度来过滤掉太短的标符。

以下是用于清理评论代码的更新版本。

代码语言:js
复制
from nltk.corpus import stopwords
import string
 
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# load the document
filename = 'txt_sentoken/neg/cv000_29416.txt'
text = load_doc(filename)
# split into tokens by white space
tokens = text.split()
# remove punctuation from each token
table = str.maketrans('', '', string.punctuation)
tokens = [w.translate(table) for w in tokens]
# remove remaining tokens that are not alphabetic
tokens = [word for word in tokens if word.isalpha()]
# filter out stop words
stop_words = set(stopwords.words('english'))
tokens = [w for w in tokens if not w in stop_words]
# filter out short tokens
tokens = [word for word in tokens if len(word) > 1]
print(tokens)

运行这个例子,得到了一个更清晰的标符列表

代码语言:js
复制
 'explanation', 'craziness', 'came', 'oh', 'way', 'horror', 'teen', 'slasher', 'flick', 'packaged', 'look', 'way', 'someone', 'apparently', 'assuming', 'genre', 'still', 'hot', 'kids', 'also', 'wrapped', 'production', 'two', 'years', 'ago', 'sitting', 'shelves', 'ever', 'since', 'whatever', 'skip', 'wheres', 'joblo', 'coming', 'nightmare', 'elm', 'street', 'blair', 'witch', 'crow', 'crow', 'salvation', 'lost', 'highway', 'memento', 'others', 'stir', 'echoes']

我们可以把它送进一个名为clean_doc()的函数中,并在另一个积极的评论中进行测试。

代码语言:js
复制
from nltk.corpus import stopwords
import string
 
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # remove punctuation from each token
    table = str.maketrans('', '', string.punctuation)
    tokens = [w.translate(table) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
 
# load the document
filename = 'txt_sentoken/pos/cv000_29590.txt'
text = load_doc(filename)
tokens = clean_doc(

再次,清理程序似乎产生了一套很好的标符,至少作为第一次清理是足够好的。

代码语言:js
复制
 'comic', 'oscar', 'winner', 'martin', 'childs', 'shakespeare', 'love', 'production', 'design', 'turns', 'original', 'prague', 'surroundings', 'one', 'creepy', 'place', 'even', 'acting', 'hell', 'solid', 'dreamy', 'depp', 'turning', 'typically', 'strong', 'performance', 'deftly', 'handling', 'british', 'accent', 'ians', 'holm', 'joe', 'goulds', 'secret', 'richardson', 'dalmatians', 'log', 'great', 'supporting', 'roles', 'big', 'surprise', 'graham', 'cringed', 'first', 'time', 'opened', 'mouth', 'imagining', 'attempt', 'irish', 'accent', 'actually', 'wasnt', 'half', 'bad', 'film', 'however', 'good', 'strong', 'violencegore', 'sexuality', 'language', 'drug', 'content']
 

还有更多的清理步骤我们可以进行,我把它们留给你去想象。

接下来,我们来看看如何管理标符的首选词汇表。

4.开发词汇表

在处理文本的预测模型,如词袋模型时,要减小词汇表的规模是不太容易的。

词汇表越大,每个单词或文档的代表的内容就越少。

为情感分析预处理文本工作的一部分,包括定义和定制模型支持词汇的词汇表。

我们可以通过加载数据集中的所有文档并构建一组单词来实现这一点。我们可能决定支持所有这些单词,也许放弃一些单词。然后可以将最终选中的词汇表保存到文件中供以后调用,例如将来在新文档中过滤单词。

我们可以跟踪计数器中的词汇表,计数器是一个单词与其计数的词典,再加上一些额外的便利功能。

我们需要开发一个新的函数来处理一个文档并将其添加到词汇表中。该函数需要通过调用之前开发的load_doc()函数来加载文档。它需要使用先前开发的clean_doc()函数来清理加载的文档,然后它需要将所有的标符添加到计数器,并更新计数。我们可以通过调用counter对象上的update()函数来完成这最后一步。

下面是一个名为add_doc_to_vocab()的函数,它将文档文件名和计数器词汇表作为参数。

代码语言:js
复制
# load doc and add to vocab
def add_doc_to_vocab(filename, vocab):
    # load doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # update counts
    vocab.update(tokens)

最后,我们可以使用上面的模板来处理名为process_docs()的目录中的所有文档,并更新它以调用add_doc_to_vocab()

代码语言:js
复制
# load all docs in a directory
def process_docs(directory, vocab):
    # walk through all files in the folde
    for filename in listdir(directory):
        # skip files that do not have the right extension
        if not filename.endswith(".txt"):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # add doc to vocab
        add_doc_to_vocab(path, vocab)

我们可以将所有这些放在一起,并利用数据集中的所有文档开发出完整的词汇表。

代码语言:js
复制
from string import punctuation
from os import listdi
from collections import Counte
from nltk.corpus import stopwords
 
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # remove punctuation from each token
    table = str.maketrans('', '', punctuation)
    tokens = [w.translate(table) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
 
# load doc and add to vocab
def add_doc_to_vocab(filename, vocab):
    # load doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # update counts
    vocab.update(tokens)
 
# load all docs in a directory
def process_docs(directory, vocab):
    # walk through all files in the folde
    for filename in listdir(directory):
        # skip files that do not have the right extension
        if not filename.endswith(".txt"):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # add doc to vocab
        add_doc_to_vocab(path, vocab)
 
# define vocab
vocab = Counter()
# add all docs to vocab
process_docs('txt_sentoken/neg', vocab)
process_docs('txt_sentoken/pos', vocab)
# print the size of the vocab
print(len(vocab))
# print the top words in the vocab
print(vocab.most_common(50))

运行示例将创建包含数据集中所有文档的词汇表,包括正面和负面的评论。

可以看到,所有的评论中总共有超过46,000个独特的单词,排名前三的单词是“ film ”,“ one ”和“ movie ”。

代码语言:js
复制
 46557
[('film', 8860), ('one', 5521), ('movie', 5440), ('like', 3553), ('even', 2555), ('good', 2320), ('time', 2283), ('story', 2118), ('films', 2102), ('would', 2042), ('much', 2024), ('also', 1965), ('characters', 1947), ('get', 1921), ('character', 1906), ('two', 1825), ('first', 1768), ('see', 1730), ('well', 1694), ('way', 1668), ('make', 1590), ('really', 1563), ('little', 1491), ('life', 1472), ('plot', 1451), ('people', 1420), ('movies', 1416), ('could', 1395), ('bad', 1374), ('scene', 1373), ('never', 1364), ('best', 1301), ('new', 1277), ('many', 1268), ('doesnt', 1267), ('man', 1266), ('scenes', 1265), ('dont', 1210), ('know', 1207), ('hes', 1150), ('great', 1141), ('another', 1111), ('love', 1089), ('action', 1078), ('go', 1075), ('us', 1065), ('director', 1056), ('something', 1048), ('end', 1047), ('still', 1038)]

也许最不常用的词,那些在所有评论中只出现一次的词,都是不可预测的。也许一些最常用的词语也没用。

这些都是很好的问题,应该用一个特定的预测模型进行测试。

一般而言,在2,000条评论中只出现一次或几次的词语很可能不具有预测性,可以从词汇表中删除,这大大减少了我们需要建模的标符数量。

我们可以通过单词及其计数来进行筛选,只有在计数高于所选阈值的情况下才进行建模。这里我们将把计数阙值设定为5次

代码语言:js
复制
# keep tokens with > 5 occurrence
min_occurane = 5
tokens = [k for k,c in vocab.items() if c >= min_occurane]
print(len(tokens))

这将词汇量从46557个减少到14803个,大幅下降。也许最少有五次是过于激进的; 你可以尝试不同的值。

然后,我们可以将所选单词的词汇保存到一个新文件中。我喜欢将词汇表保存为ASCII码,每行一个单词

下面定义了一个名为save_list()的函数,用于保存项目列表,如此,可以保存标符到文件,每行一个。

代码语言:js
复制
def save_list(lines, filename):
    data = '\n'.join(lines)
    file = open(filename, 'w')
    file.write(data)
    file.close()

下面展示了定义和保存词汇的完整示例。

代码语言:js
复制
from string import punctuation
from os import listdi
from collections import Counte
from nltk.corpus import stopwords
 
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # remove punctuation from each token
    table = str.maketrans('', '', punctuation)
    tokens = [w.translate(table) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
 
# load doc and add to vocab
def add_doc_to_vocab(filename, vocab):
    # load doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # update counts
    vocab.update(tokens)
 
# load all docs in a directory
def process_docs(directory, vocab):
    # walk through all files in the folde
    for filename in listdir(directory):
        # skip files that do not have the right extension
        if not filename.endswith(".txt"):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # add doc to vocab
        add_doc_to_vocab(path, vocab)
 
# save list to file
def save_list(lines, filename):
    data = '\n'.join(lines)
    file = open(filename, 'w')
    file.write(data)
    file.close()
 
# define vocab
vocab = Counter()
# add all docs to vocab
process_docs('txt_sentoken/neg', vocab)
process_docs('txt_sentoken/pos', vocab)
# print the size of the vocab
print(len(vocab))
# print the top words in the vocab
print(vocab.most_common(50))
# keep tokens with > 5 occurrence
min_occurane = 5
tokens = [k for k,c in vocab.items() if c >= min_occurane]
print(len(tokens))
# save tokens to a vocabulary file
save_list(tokens, 'vocab.txt')

在创建词汇表后运行最后这个的模块,将会保存所选择的单词到文件里去。

查看,甚至学习你选择的词汇表是明智的,这样可以提前有些想法,有利于未来更好的预处理这些数据或文本数据。

代码语言:js
复制
hasnt
updating
figuratively
symphony
civilians
might
fisherman
hokum
witch
buffoons
...

接下来,我们讨论如何使用词汇表来创建电影评论数据集的预处理版本。

5.保存预处理好的数据

我们可以使用数据清理和挑选好的词汇表来预处理每个电影评论,并保存准备建模的评论预处理版本。

这是一个很好的做法,因为它可以将数据准备与建模分离开来,使您可以专注于建模。并在您有新想法后随时回到数据准备上。

我们可以从加载“ vocab.txt ” 词汇表开始。

代码语言:js
复制
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# load vocabulary
vocab_filename = 'review_polarity/vocab.txt'
vocab = load_doc(vocab_filename)
vocab = vocab.split()
vocab = set(vocab)

接下来,我们要清理评论,使用加载的词汇表来过滤不需要的标符,并将干净的评论保存在一个新文件中。

一种方法是将所有正面评论保存在一个文件中,将所有负面评论保存在另一个文件中,对于每个评论,在单独的行上将滤过的标符用空格分割。

首先,我们可以定义一个函数来处理一个文档,清理它,过滤它,并将它作为一个可以保存在文件中的单行来返回。下面定义了doc_to_line()函数,将文件名和词汇表(设为一个集合)作为参数。

它调用之前定义的load_doc()函数来加载文档,并使用clean_doc()由文档得到标符

代码语言:js
复制
# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)

接下来,我们可以定义一个新版本的process_docs()函数来遍历文件夹中的所有评论,并通过为每个文档调用doc_to_line()将它们转换为行。然后返回行的列表。

代码语言:js
复制
# load all docs in a directory
def process_docs(directory, vocab):
    lines = list()
    # walk through all files in the folde
    for filename in listdir(directory):
        # skip files that do not have the right extension
        if not filename.endswith(".txt"):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines

然后,我们可以对正面和负面评论的目录调用 process_docs() 方法,然后调用上一节中的save_list()方法将每个处理后的评论列表保存到一个文件中。

下面提供了完整的代码。

代码语言:js
复制
from string import punctuation
from os import listdi
from collections import Counte
from nltk.corpus import stopwords
 
# load doc into memory
def load_doc(filename):
    # open the file as read only
    file = open(filename, 'r')
    # read all text
    text = file.read()
    # close the file
    file.close()
    return text
 
# turn a doc into clean tokens
def clean_doc(doc):
    # split into tokens by white space
    tokens = doc.split()
    # remove punctuation from each token
    table = str.maketrans('', '', punctuation)
    tokens = [w.translate(table) for w in tokens]
    # remove remaining tokens that are not alphabetic
    tokens = [word for word in tokens if word.isalpha()]
    # filter out stop words
    stop_words = set(stopwords.words('english'))
    tokens = [w for w in tokens if not w in stop_words]
    # filter out short tokens
    tokens = [word for word in tokens if len(word) > 1]
    return tokens
 
# save list to file
def save_list(lines, filename):
    data = '\n'.join(lines)
    file = open(filename, 'w')
    file.write(data)
    file.close()
 
# load doc, clean and return line of tokens
def doc_to_line(filename, vocab):
    # load the doc
    doc = load_doc(filename)
    # clean doc
    tokens = clean_doc(doc)
    # filter by vocab
    tokens = [w for w in tokens if w in vocab]
    return ' '.join(tokens)
 
# load all docs in a directory
def process_docs(directory, vocab):
    lines = list()
    # walk through all files in the folde
    for filename in listdir(directory):
        # skip files that do not have the right extension
        if not filename.endswith(".txt"):
            continue
        # create the full path of the file to open
        path = directory + '/' + filename
        # load and clean the doc
        line = doc_to_line(path, vocab)
        # add to list
        lines.append(line)
    return lines
 
# load vocabulary
vocab_filename = 'vocab.txt'
vocab = load_doc(vocab_filename)
vocab = vocab.split()
vocab = set(vocab)
# prepare negative reviews
negative_lines = process_docs('txt_sentoken/neg', vocab)
save_list(negative_lines, 'negative.txt')
# prepare positive reviews
positive_lines = process_docs('txt_sentoken/pos', vocab)
save_list(positive_lines, 'positive.txt')

运行示例保存到两个新文件中,分别名为“ negative.txt ”和“ positive.txt ”,分别包含预处理好的正面和反面评论。

数据已经准备好用在一个词袋甚至是文字嵌入模型中。

扩展

本节列出了您可能希望探索的一些扩展。

  • 词干。我们可以使用像Porter stemmer这样的词干算法将文档中的每个单词都缩减为词干。
  • 多单词。除了专注于单个单词,我们还可以开发词对的单词表。即双词。我们甚至还可以考察使用更大的词组,例如三词,以及多词。
  • 编码词。我们可以保存单词的整数编码,而不是按原样保存标符,用唯一的整数作为索引来代表单词表中的每个单词。这将使建模时更容易处理数据。
  • 编码文档。我们不用在文档中保存标符,而是使用词袋模型对文档进行编码,并将每个单词编码为布尔型存在/不存在。或者使用更复杂的评分方式,如TF-IDF。

如果你尝试任何这些扩展,我很想知道。 在下面的评论中分享你的结果。

进一步阅读

如果您正在深入研究,本节将提供更多有关该主题的资源。

数据集

接口

总结

在本教程中,您将一步一步了解了如何为情感分析预处理电影评论文本数据。

具体来说,你了解到:

  • 如何加载文本数据并清理它以去除标点符号和其他非单词内容。
  • 如何开发词汇表,定制词汇表,并将其保存到文件中。
  • 如何使用预定义的词汇表和清理方法来预处理电影评论,并将其保存到新的文件中以供建模。
评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 教程概览
  • 需要有关文本数据深度学习的帮助?
  • 1.电影评论数据集
  • 2.加载文本数据
  • 3.清理文本数据
  • 4.开发词汇表
  • 5.保存预处理好的数据
  • 扩展
  • 进一步阅读
    • 数据集
      • 接口
      • 总结
      相关产品与服务
      NLP 服务
      NLP 服务(Natural Language Process,NLP)深度整合了腾讯内部的 NLP 技术,提供多项智能文本处理和文本生成能力,包括词法分析、相似词召回、词相似度、句子相似度、文本润色、句子纠错、文本补全、句子生成等。满足各行业的文本智能需求。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档