群团组织网站建设,wordpress 数据库连接文件,云服务器 做网站,做企业网站必须要座机吗最近总结修改了下预处理方法#xff0c;记录下 首先download需要的依赖
pip install pyenchantpip install nltk pyenchant 是用来检测拼写正确的#xff0c;如果你的文本里面可能包含非正确拼写的单词#xff0c;那就忽略它#xff0c;nltk用来做分词的。
python -m nlt… 最近总结修改了下预处理方法记录下 首先download需要的依赖
pip install pyenchantpip install nltk pyenchant 是用来检测拼写正确的如果你的文本里面可能包含非正确拼写的单词那就忽略它nltk用来做分词的。
python -m nltk.downloader punkt
python -m nltk.downloader stopwords
from nltk.corpus import stopwords
import nltk
import enchant
import redef is_spelled_correctly(word, languageen_US):spell_checker enchant.Dict(language)return spell_checker.check(word)def preprocess_text(text):text re.sub(r\W, ,re.sub(r[0-9], , text.replace(-, ).replace(_, )))wordsnltk.word_tokenize(text)stop_words set(stopwords.words(english))words [item for word in words for item in re.findall(r[A-Z][a-z]*|[a-z], word)if is_spelled_correctly(item) and item.lower() not in stop_words]return .join(words).lower()if __name__ __main__:print(preprocess_text(ServiceHandlerId caedbe-85432-xssc-dsdabffdddbea An exception of some microservice TargetDownService occurred and was test #/*-sss ))
#service handler id exception target service occurred test 这里最后再转小写是因为防止ServiceHandlerId这种连续的单词链接成的字符串被拼写检查剔除只有保持驼峰情况下才能用 re.findall(r[A-Z][a-z]*|[a-z], word) 成功把他分成单独的单词所以最后再处理大小写。
改进方案1
之后测试的时候发现数据量一大他就很慢后面优化了一下速度大大提升了
from nltk.corpus import stopwords
import nltk
import enchant
import respell_checker enchant.Dict(language)def memoize(func):cache {}def wrapper(*args):if args not in cache:cache[args] func(*args)return cache[args]return wrappermemoize
def check_spelling(word):return spell_checker.check(word)def preprocess_text(text):text re.sub(r\W, ,re.sub(r[0-9], , text.replace(-, ).replace(_, )))wordsnltk.word_tokenize(text)stop_words set(stopwords.words(english))words [item for word in words for item in re.findall(r[A-Z][a-z]*|[a-z], word)if check_spelling(item) and item.lower() not in stop_words]return .join(words).lower()if __name__ __main__:print(preprocess_text(ServiceHandlerId caedbe-85432-xssc-dsdabffdddbea An exception of some microservice TargetDownService occurred and was test #/*-sss ))
#service handler id exception target service occurred test这里面使用了memoization 技术它是一种将函数调用和结果存储在一个字典中的优化技术。我这里用来缓存单词的拼写检查结果。
这样之后数据量大了之后速度依然不会太慢了。
改进方案2
使用spellchecker 这个的速度就比enchant 快的多
pip install pyspellchecker
spell SpellChecker()
def preprocess_text(text):text re.sub(r\W, ,re.sub(r[0-9], , text.replace(-, ).replace(_, )))wordsnltk.word_tokenize(text)stop_words set(stopwords.words(english))words [item for word in words for item in spell.known(re.findall(r[A-Z][a-z]*|[a-z], word)) if item.lower() not in stop_words]return .join(words).lower()
区别
SpellChecker是一个基于编辑距离的拼写检查库它可以在内存中加载一个词典并对给定的单词列表进行快速的拼写检查。enchant是一个基于C语言的拼写检查库它可以使用不同的后端如aspell, hunspell, ispell等来检查单词是否存在于词典中。SpellChecker比enchant更快尤其是当单词列表很大时。