从文本构建新特征

Python 中的情感分析

Violeta Misheva

Data Scientist

视频目标

 

目标:用与文本列相关的特征(反映情感)丰富现有数据集

Python 中的情感分析

商品评论数据

reviews.head()

亚马逊商品评论前5行

Python 中的情感分析

从评论列提取特征

 

  • 每条评论有多长?
  • 包含多少句子?
  • 涉及哪些词性?
  • 有多少标点?
Python 中的情感分析

对字符串分词

from nltk import word_tokenize
anna_k = 'Happy families are all alike, every unhappy family is unhappy in its own way.'
word_tokenize(anna_k)

['Happy','families','are', 'all','alike',',',
 'every','unhappy', 'family', 'is','unhappy','in',
 'its','own','way','.']
Python 中的情感分析

从列中获取分词

# General form of list comprehension
[expression for item in iterable]
word_tokens = [word_tokenize(review) for review in reviews.review]
type(word_tokens)
list
type(word_tokens[0])
list
Python 中的情感分析

从列中获取分词

len_tokens = []

# Iterate over the word_tokens list
for i in range(len(word_tokens)):
     len_tokens.append(len(word_tokens[i]))

# Create a new feature for the length of each review
reviews['n_tokens'] = len_tokens
Python 中的情感分析

处理标点符号

  • 我们之前未处理,但可将其排除
  • 可加入一个统计标点数量的特征
    • 标点很多的评论可能情绪更强烈
Python 中的情感分析

含长度特征的评论

reviews.head()

亚马逊商品评论前5行,包括新增的评论长度列

Python 中的情感分析

Vamos praticar!

Python 中的情感分析

Preparing Video For Download...