python jieba分词去除停用词
时间: 2023-09-04 18:16:16 浏览: 112
你可以使用 Python 中的 jieba 库来进行中文分词,并使用自定义的停用词表来去除停用词。以下是一个示例代码:
```python
import jieba
# 读取停用词表
stopwords_path = 'stopwords.txt'
stopwords = [line.strip() for line in open(stopwords_path, 'r', encoding='utf-8').readlines()]
# 分词并去除停用词
text = "我爱自然语言处理"
words = jieba.cut(text)
result = []
for word in words:
if word not in stopwords:
result.append(word)
print(result)
```
其中,停用词表可以自己定义或者使用已有的停用词表。在上面的示例中,停用词表的文件路径为 `stopwords.txt`,它包含了一些常见的停用词。分词后,将不在停用词表中的词加入结果列表 `result` 中。
相关问题
jieba分词后去除停用词 python
使用 jieba 库分词后,可以通过去除停用词来进一步提高分词效果。以下是使用 jieba 库和中文停用词表对一个句子进行分词并去除停用词的示例代码:
```python
import jieba
from jieba import analyse
stopwords_file = "stopwords.txt"
sentence = "我爱自然语言处理,也喜欢机器学习和深度学习。"
# 加载停用词表
stopwords = set()
with open(stopwords_file, "r", encoding="utf-8") as f:
for line in f:
stopwords.add(line.strip())
# 分词并去除停用词
words = jieba.cut(sentence)
filtered_words = []
for word in words:
if word not in stopwords:
filtered_words.append(word)
print("分词结果:", "/".join(filtered_words))
```
其中,stopwords.txt 是包含中文停用词的文本文件,可以从网上下载。在上述代码中,我们使用了 Python 的 set 数据结构来存储停用词,然后在分词过程中将停用词过滤掉。最后输出过滤后的分词结果,结果如下:
```
分词结果: 爱/自然语言处理/喜欢/机器学习/深度学习
```
csv中文分词去除停用词代码
以下是一个用 Python 实现的简单的中文分词和去除停用词的代码:
```python
import jieba
import re
# 加载停用词表
stopwords = set()
with open('stopwords.txt', 'r', encoding='utf-8') as f:
for line in f:
stopwords.add(line.strip())
# 定义中文分词函数
def chinese_word_cut(text):
# 使用正则表达式去除非中文字符
text = re.sub('[^\u4e00-\u9fa5]', '', text)
# 分词
words = jieba.lcut(text)
# 去除停用词
words = [word for word in words if word not in stopwords]
# 返回分词结果
return words
# 测试代码
text = '这是一段中文文本,包含了一些常见的停用词。'
words = chinese_word_cut(text)
print(words)
```
其中 `jieba` 是一个常用的中文分词库,需要使用 `pip install jieba` 命令安装。停用词表可以自己制作,也可以从网上下载。