在python程序的jieba库编程中,我想把seg_list加到words里面,给我一段代码吧,谢谢
时间: 2024-05-05 21:18:54 浏览: 4
下面是将 seg_list 添加到 words 中的示例代码:
```python
import jieba
# 分词
seg_list = jieba.cut("我爱自然语言处理")
# 将分词结果添加到列表中
words = []
for word in seg_list:
words.append(word)
print(words) # 输出 ['我', '爱', '自然语言处理']
```
请注意,可以使用列表推导式等更简洁的方式来实现相同的效果。
相关问题
Python编写程序利用jieba库进行分词,统计出三国演义中三国人物的出现次数
好的,首先需要安装jieba库,可以使用以下命令进行安装:
```
pip install jieba
```
然后,我们需要读取三国演义的文本文件。假设三国演义的文本文件名为“sgyy.txt”,可以使用以下代码进行读取:
```python
with open('sgyy.txt', 'r', encoding='utf-8') as f:
sgyy_text = f.read()
```
接下来,我们需要使用jieba库进行分词。可以使用以下代码:
```python
import jieba
# 分词
seg_list = jieba.cut(sgyy_text)
# 去除停用词
stop_words = [',', '。', '、', ':', ';', '\n', '之', '也', '而', '乃', '其', '则', '者', '其', '为', '以', '有', '是', '在', '不', '而', '此', '彼']
word_list = [word for word in seg_list if word not in stop_words]
```
上面的代码中,我们使用了jieba.cut()方法对文本进行分词,并使用列表推导式去除了一些无意义的停用词。
接下来,我们需要统计出三国演义中三国人物的出现次数。可以使用以下代码:
```python
# 统计人物出现次数
person_dict = {}
for i in range(len(word_list)-1):
if word_list[i] == '曹操' or word_list[i] == '刘备' or word_list[i] == '孙权':
if word_list[i+1] != ',' and word_list[i+1] != '。':
if word_list[i] not in person_dict:
person_dict[word_list[i]] = 1
else:
person_dict[word_list[i]] += 1
# 输出结果
for key, value in person_dict.items():
print(key, value)
```
上面的代码中,我们使用了一个字典来统计人物出现次数。首先,我们遍历分词后的列表,判断当前词是否是三国人物中的一个(曹操、刘备、孙权)。如果当前词是一个三国人物,我们再判断下一个词是否是标点符号(“,”和“。”),如果不是,则将当前词加入到字典中,并将其出现次数加1。最后,我们将字典中统计出来的结果输出即可。
完整代码如下:
```python
import jieba
# 读取文本
with open('sgyy.txt', 'r', encoding='utf-8') as f:
sgyy_text = f.read()
# 分词
seg_list = jieba.cut(sgyy_text)
# 去除停用词
stop_words = [',', '。', '、', ':', ';', '\n', '之', '也', '而', '乃', '其', '则', '者', '其', '为', '以', '有', '是', '在', '不', '而', '此', '彼']
word_list = [word for word in seg_list if word not in stop_words]
# 统计人物出现次数
person_dict = {}
for i in range(len(word_list)-1):
if word_list[i] == '曹操' or word_list[i] == '刘备' or word_list[i] == '孙权':
if word_list[i+1] != ',' and word_list[i+1] != '。':
if word_list[i] not in person_dict:
person_dict[word_list[i]] = 1
else:
person_dict[word_list[i]] += 1
# 输出结果
for key, value in person_dict.items():
print(key, value)
```
python去停用词-python使用jieba实现中文分词去停用词方法示例
好的,下面是python使用jieba实现中文分词去停用词的示例代码:
```python
import jieba
import jieba.analyse
# 加载自定义停用词表
jieba.analyse.set_stop_words("stopwords.txt")
# 待分词文本
text = "我喜欢学习自然语言处理"
# 中文分词
seg_list = jieba.cut(text)
# 去除停用词
final_list = []
for word in seg_list:
if word not in jieba.analyse.get_stop_words():
final_list.append(word)
# 输出结果
print(final_list)
```
其中,`stopwords.txt`是自定义的停用词表,可以根据实际需要进行修改。在分词之前,先使用`set_stop_words`方法加载停用词表;在分词之后,使用`get_stop_words`方法获取停用词表,并将不在停用词表中的词加入到最终的分词结果中。