注:本博客基于python3.7 Anaconda
使用到的库
import nltk
from nltk import word_tokenize
import simplejson as jsons
import sklearn
from sklearn.feature_extraction.text import *
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
在文本预处理中,主要使用了nltk库,此外,nltk有可能需要手动下载一些包。
由于输入文本是json文件,我们需要用到simplejson读取。
sklearn主要用作后续的逻辑回归模型。
文本预处理分解函数
letter_percentage函数
- 参数:
text: 字符串
letter: 字符(小写) - 返回值:在字符串中特定字符出现的百分比(不考虑大小写)
def letter_percentage(text, letter):
print("输入字符串为:", text)
#把字符串中所有字母字符按照小写提取到list中
charlist = [char.lower() for char in text if char.isalpha()]
#创建一个fdist对象来储存所有字符
fdist = nltk.FreqDist(charlist)
#计算特定字符letter出现的百分比
frequency = fdist.freq(letter)
character_percent = 100*frequency
p = '{0:.2f}'.format(character_percent)
print(letter,'字符在输入语句中占百分比为', p)
return character_percent
Tokenization(标记化)
token:
文本字符串或文档的字符组
单一的“单词” + 可能的数字,标点等等
tokenization是文本预处理中很重要的一步。它的目的是接收一个字符串,或者一个list,内为nltk.text.Text类型的tokens。
接下来,把输入转换为单词的tokens,再把这些tokens用’universal’的标签集运行nltk的语言解释器。‘
tokenizer主要省略空格,标点等。
parts_of_speech函数
- 参数:
s: 字符串
printflag: 1为打印输入字符串,0为不打印 - 返回值:一个包含tokens和他们的POS标签的list
def parts_of_speech(s,printflag):
'''例子:
s = 'This is a sentence. And this is a second sentence! Cool.'
z1, z2 = parts_of_speech(s,0)
Tokens的总数量为14
Tag: DET Percentage of tokens = 28.57
Tag: . Percentage of tokens = 21.43
Tag: NOUN Percentage of tokens = 21.43
....
'''
if printflag ==