from nltk.corpus import treebank
t = treebank.parsed_sents('wsj_0001.mrg')[0]
t.draw()
这段代码主要为将给定文本中的英文单词进行分词并去除停用词,最后进行拼写检查,以下为代码注释:
# 导入需要用到的库
import re
import nltk
from enchant.checker import SpellChecker
from nltk.corpus import stopwords
# 给定文本,去除中文
text = 'I amm我是 一个普通的喜欢篮球的男生啊 jast a booy, and (( loved 我baskerball 还a lot. Just a lucky boy喜欢.'
text = re.sub('[\u4e00-\u9fa5]','',text) # 去除中文
print('去除中文后:')
print(text)
# 正则表达式分词
part = r"""(?x)
(?:[A-Z]\.)+
|\d+(?:\.\d+)?%?
|\w+(?:[-']\w+)*
|\.\.\.
|\S\w*
|\w+
|(?:[.,;"'?():-_`])
"""
texti = nltk.regexp_tokenize(text,part)
print('使用nltk库正则表达式对文本进行分词处理:')
print(nltk.regexp_tokenize(text,part)) # 使用nltk库的正则表达式分词器
print('使用re正则表达式对文本进行分词处理:')
print(re.findall(part,text)) # 使用re正则表达式方法
# 去除停用词
stopwordd = set(stopwords.words('english'))
word = [i for i in texti if i not in stopwordd]
print('去除停用词后:')
print(word)
# 拼写检查
spell = SpellChecker("en_US")
spell.set_text(text)
t = 0 # 用标记变量t记录错误单词数量
errword = [] # 存储错误单词
for j in spell:
t = t + 1
errword.append(j.word)
print('共发现错误的词数为:'+str(t))
print('这些拼写错误的单词依次为:')
print(errword)