nltk:python自然语言处理三 标准化

文本的标注化处理主要涉及清楚标点符号、统一大小写、数字的处理、扩展缩略词等文本的规范化操作

1.清除标点

import re
import string
from nltk import word_tokenize

text = """
I Love there things in this world. 
Sun, Moon and You. 
Sun for morning, Moon for
night, and You forever. 
"""
# 分词
words = word_tokenize(text)
# ['I', 'Love', 'there', 'things', 'in', 'this', 'world', '.', 'Sun', ',', 'Moon', 'and', 'You', '.', 'Sun', 'for', 'morning', ',', 'Moon', 'for', 'night', ',', 'and', 'You', 'forever', '.']

# re.escape(string) 返回一个字符串, 其中的所有非字母数字字符都带有反斜杠
# string.punctuation 所有的(英文)标点符号
regex_punctuation = re.compile('[%s]' % re.escape(string.punctuation))
# 将每个单词中的标点全部替换为空,如果替换后为字符则过滤掉  弊端:数字的小数点、人名间隔符会被清除
new_words = filter(lambda word: word != "", [regex_punctuation.sub("", word) for word in words])
print(new_words)
# ['I', 'Love', 'there', 'things', 'in', 'this', 'world', 'Sun', 'Moon', 'and', 'You', 'Sun', 'for', 'morning', 'Moon', 'for', '20', 'do', 'nt', 'night', 'and', 'You', 'forever']

2.统一大小写

text = "I Love there things in this world. "
text.lower()
text.upper()

3.处理停用词

过滤掉大量出现又没有实际意义的词

from nltk.corpus import stopwords
# stopwords是WordListCorpusReader的一个实例 WordListCorpusReader有一个word方法用于获取停用词
# 可以通过word方法的filed参数指定获取那个语言的停用词  如果不指定会获取所有语言的停用词
# 实例的fileids方法可以查看nltk文件中都包含哪些语言的停用词库

# 使用stopwords中的英文停用词库
stop_words = set(stopwords.words("english"))
words = ['I', 'Love', 'there', 'things', 'in', 'this', 'world', 'Sun', 'Moon', 'and', 'You',
         'Sun', 'for', 'morning', 'Moon', 'for', 'night', 'and', 'You', 'forever']
# 过滤words中存在于停用词库中的单词
new_words = [word for word in words if word not in stop_words]

猜你喜欢

转载自blog.csdn.net/qq_41864652/article/details/81508268