12、邮件分类实例

本文通过Python实现邮件分类,利用正则表达式匹配关键词,详细解析邮件内容,展示算法在信息处理中的应用。
摘要由CSDN通过智能技术生成
"""
这部分用SVM建立一个垃圾邮件分类器。
你需要将每个email变成一个n维的特征向量,
这个分类器将判断给定一个邮件x是垃圾邮件(y=1)或不是垃圾邮件(y=0)。
"""
# 先来看一个邮件的数据集例子
with open('data/emailSample1.txt', 'r') as f:
    # r:以只读方式打开文件。文件的指针将会放在文件的开头。
    print(f.read())
'''
> Anyone knows how much it costs to host a web portal ?
>
Well, it depends on how many visitors you're expecting.
This can be anywhere from less than 10 bucks a month to a couple of $100. 
You should checkout http://www.rackspace.com/ or perhaps Amazon EC2 
if youre running something big..

To unsubscribe yourself from this mailing list, send an email to:
groupname-unsubscribe@egroups.com
'''

"""
可以看到,邮件内容包含 a URL, an email address(at the end), numbers, and dollar amounts. 很多邮件都会包含这些元素,但是每封邮件的具体内容可能会不一样。
因此,处理邮件经常采用的方法是标准化这些数据,把所有URL当作一样,所有数字看作一样。
例如,我们用唯一的一个字符串‘httpaddr’来替换所有的URL,来表示邮件包含URL,而不要求具体的URL内容。
这通常会提高垃圾邮件分类器的性能,因为垃圾邮件发送者通常会随机化URL,因此在新的垃圾邮件中再次看到任何特定URL的几率非常小。
我们可以做如下处理:
1. Lower-casing: 把整封邮件转化为小写。
2. Stripping HTML: 移除所有HTML标签,只保留内容。
3. Normalizing URLs: 将所有的URL替换为字符串 “httpaddr”.
4. Normalizing Email Addresses: 所有的地址替换为 “emailaddr”
5. Normalizing Dollars: 所有dollar符号($)替换为“dollar”.
6. Normalizing Numbers: 所有数字替换为“number”.
7. Word Stemming(词干提取): 将所有单词还原为词源。例如,“discount”, “discounts”, “discounted” and “discounting”都替换为“discount”.
8. Removal of non-words: 移除所有非文字类型,所有的空格(tabs, newlines, spaces)调整为一个空格.
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from sklearn import svm
import pandas as pd
import re  # 用于电子邮件处理的正则表达式
import nltk, nltk.stem.porter  # 英文分词算法

email = '''
> Anyone knows how much it costs to host a web portal ?
>
Well, it depends on how many visitors you're expecting.
This can be anywhere from less than 10 bucks a month to a couple of $100. 
You should checkout http://www.rackspace.com/ or perhaps Amazon EC2 
if youre running something big..

To unsubscribe yourself from this mailing list, send an email to:
groupname-unsubscribe@egroups.com
'''


# 做除了Word Stemming和Removal of non-words外的所有处理
def processEmail(email
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值