Home Backend Development Python Tutorial 用Python进行一些简单的自然语言处理的教程

用Python进行一些简单的自然语言处理的教程

Jun 06, 2016 am 11:22 AM
python natural language

本月的每月挑战会主题是NLP,我们会在本文帮你开启一种可能:使用pandas和python的自然语言工具包分析你Gmail邮箱中的内容。

NLP-风格的项目充满无限可能:

  •     情感分析是对诸如在线评论、社交媒体等情感内容的测度。举例来说,关于某个话题的tweets趋向于正面还是负面的意见?一个新闻网站涵盖的主题,是使用了更正面/负面的词语,还是经常与某些情绪相关的词语?这个“正面”的Yelp点评不是很讽刺么?(祝最后去的那位好运!)
  •     分析语言在文学中的使用,进而衡量词汇或者写作风格随时间/地区/作者的变化趋势.
  •     通过识别所使用的语言的关键特征,标记是否为垃圾内容。
  •     基于评论所覆盖的主题,使用主题抽取进行相似类别的划分。
  •     通过NLTK's的语料库,应用Elastisearch和WordNet的组合来衡量Twitter流API上的词语相似度,进而创建一个更好的实时Twitter搜索。
  •     加入NaNoGenMo项目,用代码生成自己的小说,你可以从这里大量的创意和资源入手。

将Gmail收件箱加载到pandas

让我们从项目实例开始!首先我们需要一些数据。准备你的Gmail的数据存档(包括你最近的垃圾邮件和垃圾文件夹)。

https://www.google.com/settings/takeout

现在去散步吧,对于5.1G大小的信箱,我2.8G的存档需要发送一个多小时。

当你得到数据并为工程配置好本地环境之后好,使用下面的脚本将数据读入到pandas(强烈建议使用IPython进行数据分析)
 

from mailbox import mbox
import pandas as pd
 
def store_content(message, body=None):
 if not body:
  body = message.get_payload(decode=True)
 if len(message):
  contents = {
   "subject": message['subject'] or "",
   "body": body,
   "from": message['from'],
   "to": message['to'],
   "date": message['date'],
   "labels": message['X-Gmail-Labels'],
   "epilogue": message.epilogue,
  }
  return df.append(contents, ignore_index=True)
 
# Create an empty DataFrame with the relevant columns
df = pd.DataFrame(
 columns=("subject", "body", "from", "to", "date", "labels", "epilogue"))
 
# Import your downloaded mbox file
box = mbox('All mail Including Spam and Trash.mbox')
 
fails = []
for message in box:
 try:
  if message.get_content_type() == 'text/plain':
   df = store_content(message)
  elif message.is_multipart():
   # Grab any plaintext from multipart messages
   for part in message.get_payload():
    if part.get_content_type() == 'text/plain':
     df = store_content(message, part.get_payload(decode=True))
     break
 except:
  fails.append(message)
Copy after login

上面使用Python的mailbox模块读取并解析mbox格式的邮件。当然还可以使用更加优雅的方法来完成(比如,邮件中包含大量冗余、重复的数据,像回复中嵌入的“>>>”符号)。另外一个问题是无法处理一些特殊的字符,简单起见,我们进行丢弃处理;确认你在这一步没有忽略信箱中重要的部分。

需要注意的是,除了主题行,我们实际上并不打算利用其它内容。但是你可以对时间戳、邮件正文进行各种各样有趣的分析,通过标签进行分类等等。鉴于这只是帮助你入门的文章(碰巧会显示来自我自己信箱中的结果),我不想去考虑太多细节。

查找常用词语

现在我们已经得到了一些数据,那么来找出所有标题行中最常用的10个词语:

# Top 10 most common subject words
from collections import Counter
 
subject_word_bag = df.subject.apply(lambda t: t.lower() + " ").sum()
 
Counter(subject_word_bag.split()).most_common()[:10]
 
[('re:', 8508), ('-', 1188), ('the', 819), ('fwd:', 666), ('to', 572), ('new', 530), ('your', 528), ('for', 498), ('a', 463), ('course', 452)]
Copy after login

嗯,那些太常见了,下面尝试对常用词语做些限制:

from nltk.corpus import stopwords
stops = [unicode(word) for word in stopwords.words('english')] + ['re:', 'fwd:', '-']
subject_words = [word for word in subject_word_bag.split() if word.lower() not in stops]
Counter(subject_words).most_common()[:10]
 
[('new', 530), ('course', 452), ('trackmaven', 334), ('question', 334), ('post', 286), ('content', 245), ('payment', 244), ('blog', 241), ('forum', 236), ('update', 220)]
Copy after login

除了人工移除几个最没价值的词语,我们也使用了NLTK的停用词语料库,使用前需要进行傻瓜式安装。现在可以看到我收件箱中的一些典型词语,但通常来讲在英文文本中并不一定同样是典型的。

二元词组和搭配词

NLTK可以进行另外一个有趣的测量是搭配原则。首先,我们来看下常用的“二元词组”,即经常一起成对出现的两个单词的集合:

from nltk import collocations
bigram_measures = collocations.BigramAssocMeasures()
bigram_finder = collocations.BigramCollocationFinder.from_words(subject_words)
 
# Filter to top 20 results; otherwise this will take a LONG time to analyze
bigram_finder.apply_freq_filter(20)
for bigram in bigram_finder.score_ngrams(bigram_measures.raw_freq)[:10]:
 print bigram
 
(('forum', 'content'), 0.005839453284373725)
(('new', 'forum'), 0.005839453284373725)
(('blog', 'post'), 0.00538045695634435)
(('domain', 'names'), 0.004870461036311709)
(('alpha', 'release'), 0.0028304773561811506)
(('default', 'widget.'), 0.0026519787841697267)
(('purechat:', 'question'), 0.0026519787841697267)
(('using', 'default'), 0.0026519787841697267)
(('release', 'third'), 0.002575479396164831)
(('trackmaven', 'application'), 0.002524479804161567)
Copy after login

我们可以对三元词组(或n元词组)重复相同的步骤来查找更长的短语。这个例子中,“new forum content”是出现次数最多的三元词组,但是在上面例子的列表中,它却被分割成两部分并位居二元词组列表的前列。

另外一个稍微不同类型的搭配词的度量是基于点间互信息(pointwise mutual information)的。本质上,它所度量的是给定一个我们在指定文本中看到的单词,相对于他们通常在全部文档中单独出现的频率,另外一个单词出现的可能性。举例来说,通常,如果我的邮件主题使用单词“blog”与/或“post”很多,那么二元组“blog post”并不是一个有趣的信号,因为一个单词仍然可能不和另一个单词同时出现。根据这条准则,我们得到一个不同的二元组的集合。

for bigram in bigram_finder.nbest(bigram_measures.pmi, 5):
 print bigram
 
('4:30pm', '5pm')
('motley', 'fool')
('60,', '900,')
('population', 'cap')
('simple', 'goods')
Copy after login

因此,我没有收到很多提到单词“motley”或者“fool”的邮件主题,但是当我看到其中任意一个,那么“Motley Fool”可能是相关联的。

情感分析

最后,让我们尝试一些情感分析。为了快速入门,我们可以使用以NLTK为基础的TextBlob库,它提供了对于大量的常用NLP任务的简单访问。我们可以使用它内建的情感分析(基于模式)来计算主题的“极性(polarity)”。从,表示高度负面情绪的-1到表示正面情绪的1,其中0为中性(缺乏一个明确的信号)

接下来:分析一段时间内的你的收件箱;看看是否能够通过邮件分类,确定正文的发送者/标签/垃圾这些基本属性。使用潜在语义索引去揭示所涵盖的最常用的常规主题。将你的发件文件夹输入到马尔科夫模型(Markov model)中,结合词性标注生成看起来连贯的自动回复

请让我们知道你是否使用NLP尝试了有趣的项目分支,包含一份开源库将作为加分点。你可以在challenge.hackpad.com看下前面的展示,以找到更多的灵感!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles