脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python基础之停用词过滤详解

python基础之停用词过滤详解

2021-10-15 11:11一无所知的程序员 Python

这篇文章主要介绍了python基础之停用词过滤详解,文中有非常详细的代码示例,对正在学习python基础的小伙伴们有很好地帮助,需要的朋友可以参考下

一、什么是停用词

在汉语中,有一类没有多少意义的词语,比如组词“的”,连词“以及”、副词“甚至”,语气词“吧”,被称为停用词。一个句子去掉这些停用词,并不影响理解。所以,进行自然语言处理时,我们一般将停用词过滤掉。

而hanlp库提供了一个小巧的停用词字典,它位于lib\site-packages\pyhanlp\static\data\dictionary目录中,名字为:stopwords.txt。该文本收录了常见的中英文无意义的词汇,每行一个词语。示例如下:

python基础之停用词过滤详解

我们在进行自然语言处理时,可以用bintrie、doublearraytrie和ahocorasickdoublearraytrie中的任意一个来存储词典。考虑到该词典中都是短语且比较多,用双数组字典树更划算,处理时间更快。

二、加载停用词字典

通过前文的介绍,我们知道了使用双数组字典树加载停用词字典更划算。下面,我们来加载其停用词,并返回键值对结构。代码如下:

?
1
2
3
4
5
6
7
def load_dictionary(path):
    map=jclass('java.util.treemap')()
    with open(path,encoding='utf-8') as src:
        for word in src:
            word=word.strip()
            map[word]=word
    return jclass('com.hankcs.hanlp.collection.trie.doublearraytrie')(map)

三、删除停用词

通过上面的停用词加载,我们获取了doublearraytrie树结构的词汇。如果要删除停用词,可以直接使用分词后的结果剔除停用词即可。剔除的方法如下:

?
1
2
def remove_stopwords(termlist,trie):
    return [term.word for term in termlist if not trie.containskey(term.word)]

四、分词以及删除停用词

在前面的博文中,我们已经学会了如何分词,现在我们又学会了如何剔除停用词。这里,我们将两者结合起来,实现分词效果。代码如下:

?
1
2
3
4
5
6
7
8
if __name__ == "__main__":
    hanlp.config.showtermnature=false
    trie=load_dictionary(hanlp.config.corestopworddictionarypath)
    text="今天就这样吧!明天我们在说可以吗?"
    segment=doublearraytriesegment()
    termlist=segment.seg(text)
    print("分词结果",termlist)
    print("去掉停用词",remove_stopwords(termlist,trie))

运行之后,得到如下结果:

python基础之停用词过滤详解

五、直接删除停用词(不分词)

对应上面的结果,我们先分词在删除停用词。但是,有时候我们也喜欢先删除停用词在进行分词。下面,我们来实现直接删除停用词。

代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#直接过滤方法
def direct_remove_stopwords(text,replacement,trie):
    jstring=jclass('java.lang.string')
    searcher=trie.getlongestsearcher(jstring(text),0)
    offset=0
    result=''
    while searcher.next():
        begin=searcher.begin
        end=begin+searcher.length
        if begin>offset:
            result+=text[offset:begin]
            result+=replacement
            offset=end
    if offset<len(text):
        result+=text[offset:]
    return result
 
 
if __name__ == "__main__":
    hanlp.config.showtermnature = false
    trie = load_dictionary(hanlp.config.corestopworddictionarypath)
    text = "今天就这样吧!明天我们在说可以吗?"
    segment = doublearraytriesegment()
    termlist = segment.seg(text)
    print("分词结果", termlist)
    print("去掉停用词", remove_stopwords(termlist, trie))
    print("不分词去掉停用词", direct_remove_stopwords(text, "**", trie))

运行之后,效果如下:

python基础之停用词过滤详解

到此这篇关于python基础之停用词过滤详解的文章就介绍到这了,更多相关python停用词过滤内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/liyuanjinglyj/article/details/115025806

延伸 · 阅读

精彩推荐