函数说明:

 1. re.sub(r'[^a-zA-Z0-9\s]', repl='', sting=string)  用于进行字符串的替换,这里我们用来去除标点符号

 参数说明:r'[^a-zA-Z0-9\s]' 配对的模式,^表示起始位置,\s表示终止位置,[]表示取中间部分,这个的意思是找出除字符串大小写或者数字组成以外的东西,repl表示使用什么进行替换,这里使用'',即直接替换,string表示输入的字符串

2. stopwords = nltk.corpus.stopwords.words('english') # 表示获得英文的停用词表, 使用nltk.download下载停用词表

3. nltk.WordPunctTokenizer() 构建模型,使用.tokenize(str) 对字符串进行分词操作

4. np.vectorize(函数)  表示对函数进行向量化操作,使得对函数输入的参数如果是列表形式,输入的时候一个个输入,输出的时候也是一个个输出

5.sklearn.extract_features.text.CountVectorizer  构建词频词袋模型,.get_feature_names获得词袋模型的标签 

在一个文本数据输入的时候,我们需要对其做数字编码,一种就是根据文本出现的次数做一个词袋模型

 

当一个文本数据输入的时候

          第一步:去除标点符号,并进行分词操作(使用nltk.WordPunctTokenizer().tokenize进行分词操作) 

          第二步:依据生成的停用词表,去除停用词,并且使用‘ ’.join进行串接,为了下一步的词袋模型做准备

          第三步:使用CountVectorizer, 对向量进行词频统计,将文本数据进行向量化操作,使用.get_feature_names()获得词袋中的词语的名字

 

代码:

        第一步:构建DateFrame格式,同时数组化数据

        第二步:载入停用词表nltk.corpus.stopwords.words('english')和构建分词nltk.WordPunctTokenize()模型,定义函数Normalize_corpus:使用re.sub去除标点符号, 使用.tokenize进行分词,将分完成的列表,使用停用表去除停用词,最后使用' '.join连接分词后的列表为下一步构造词袋模型做准备

        第三步: 使用np.vectorize(Normalize_corpus) 对函数进行向量化操作,调用函数对列表进行分词和去除停用词的操作

        第四步:使用sklearn.feature_extraction.text import CountVectorizer 构建词频的词袋模型,使用.get_feature_names获得词袋模型的特征标签

import pandas as pd
import numpy as np
import re
import nltk #pip install nltk


corpus = ['The sky is blue and beautiful.',
          'Love this blue and beautiful sky!',
          'The quick brown fox jumps over the lazy dog.',
          'The brown fox is quick and the blue dog is lazy!',
          'The sky is very blue and the sky is very beautiful today',
          'The dog is lazy but the brown fox is quick!'
]

labels = ['weather', 'weather', 'animals', 'animals', 'weather', 'animals']

# 第一步:构建DataFrame格式数据
corpus = np.array(corpus)
corpus_df = pd.DataFrame({'Document': corpus, 'categoray': labels})

# 第二步:构建函数进行分词和停用词的去除
# 载入英文的停用词表
stopwords = nltk.corpus.stopwords.words('english')
# 建立词分割模型
cut_model = nltk.WordPunctTokenizer()
# 定义分词和停用词去除的函数
def Normalize_corpus(doc):
# 可以使用re.findall(r'[a-zA-Z0-9]+', doc.lower()) 直接去除标点符号和进行分词构造词列表
# 去除字符串中结尾的标点符号 doc = re.sub(r'[^a-zA-Z0-9\s]', '', string=doc) # 是字符串变小写格式 doc = doc.lower() # 去除字符串两边的空格 doc = doc.strip() # 进行分词操作 tokens = cut_model.tokenize(doc) # 使用停止用词表去除停用词 doc = [token for token in tokens if token not in stopwords] # 将去除停用词后的字符串使用' '连接,为了接下来的词袋模型做准备 doc = ' '.join(doc) return doc # 第三步:向量化函数和调用函数 # 向量化函数,当输入一个列表时,列表里的数将被一个一个输入,最后返回也是一个个列表的输出
# norm_corpus = corpus_df['Document'].apply(Normalize_vector) 也可以使用DateFrame格式中的apply进行应用
Normalize_corpus = np.vectorize(Normalize_corpus) # 调用函数进行分词和去除停用词 corpus_norm = Normalize_corpus(corpus) # 第四步:使用CountVectorizer做词频的词袋模型 from sklearn.feature_extraction.text import CountVectorizer Cv = CountVectorizer() Cv.fit(corpus_norm) # 使用.get_feature_names()获得词袋模型的特征标签 corpus_names = Cv.get_feature_names() corpus_array = Cv.transform(corpus_norm).toarray() corpus_df = pd.DataFrame(corpus_array, columns=corpus_names) print(corpus_df.head())

posted on 2019-01-26 18:50  python我的最爱  阅读(2021)  评论(0编辑  收藏  举报