(五)N-gram语言模型的数据处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hao5335156/article/details/82733000

一、步骤

数据集说明:一段英文
(1)分词:把原始的英文分词,只保留词之间的顺序不变,多个句子也是看出整体进行分词。
(2)统计词频:按照n元进行词频统计,比如“I love NLP I enjoy it”当n=2时候,可以划分为(【I love】,【love NLP】,【NLP I】…),分别统计【I love】,【love NLP】等出现的次数。(在朴素贝叶斯中只是统计一个词,这里是统计n个前后关联的词)
(3)对统计好的词进行大到小的排序,取m和词作为特征向量
其他步骤同文本分类步骤

二、代码

# -*- coding:utf-8 -*-
import urllib2
import re
import string
import operator


def cleanText(input):
    input = re.sub('\n+', " ", input).lower()  # 匹配换行,用空格替换换行符
    input = re.sub('\[[0-9]*\]', "", input)  # 剔除类似[1]这样的引用标记
    input = re.sub(' +', " ", input)  # 把连续多个空格替换成一个空格
    input = bytes(input)  # .encode('utf-8') # 把内容转换成utf-8格式以消除转义字符
    # input = input.decode("ascii", "ignore")
    return input


def cleanInput(input):
    input = cleanText(input)
    cleanInput = []
    input = input.split(' ')  # 以空格为分隔符,返回列表

    for item in input:
        item = item.strip(string.punctuation)  # string.punctuation获取所有标点符号

        if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
            cleanInput.append(item)
    return cleanInput


def getNgrams(input, n):
    #把一段英文处理成一个个词语,保留了分词后每个词在原短文中的顺序
    input = cleanInput(input)

    output = {}  # 构造字典
    for i in range(len(input) - n + 1):
        ngramTemp = " ".join(input[i:i + n])
        if ngramTemp not in output:  # 词频统计
            output[ngramTemp] = 0
        output[ngramTemp] += 1
    return output


# 获取数据,content为一段英文
content = urllib2.urlopen(urllib2.Request("http://pythonscraping.com/files/inaugurationSpeech.txt")).read()
#2-grams
ngrams = getNgrams(content, 2)
sortedNGrams = sorted(ngrams.items(), key=operator.itemgetter(1), reverse=True)  # =True 降序排列
print(sortedNGrams)

猜你喜欢

转载自blog.csdn.net/hao5335156/article/details/82733000