jieba分词时替换多种中文(英文)符号的方法

在这里插入图片描述

  • 比如在中文分词前,将中文逗号、中文句号、中文冒号、中文引号,英文空格替换为空字符。

replace方法

  • 第6-7行代码实现替换功能。
import jieba
d = {}
with open("sgld.txt","r",encoding ="utf-8") as f:
    lssgld = f.readlines()
for word in lssgld:
    word = word.replace(',','').replace('。','').replace('“','').replace('”','').replace(':','').replace(' ','').replace('\n','')
    wo = jieba.lcut(word)
    for w in wo:
        d[w] = d.get(w,0) + 1
ls = list(d.items())                              #要理解这行代码
ls.sort(key=lambda x:x[1], reverse = True)
for j in range(5):
    print(ls[j][0],end='、')

for循环的方法

  • 第7-9 行代码实现替换功能。
import jieba                    #导入中文分词库,这是必考点
with open("sgld.txt","r",encoding ="utf-8")as f:  #使用with语句以只读方式打开文件
    lssgld = f.readlines()                        #按行读取文件构建lssgld列表

d = {}                                  #定义空字典
for ls in lssgld:
    ls = ls.replace("\n","")            #数据清洗:去掉每一行最后的换行符
    for c in "。,:”“ ":                       #中文分词前,将中文逗号、中文句号、中文冒号、中文引号,英文空格替换为空字符
        ls = ls.replace(c, "")      #使用字符串函数replace将
    wordlist = jieba.cut(ls)        #对每行进行中文分词
    for word in wordlist:
        d[word] = d.get(word,0) + 1   #构建字典

ls = list(d.items())
ls.sort(key=lambda x:x[1], reverse = True)  #列表排序

for i in range(5):
    a = ls[i][0]
    print("{}".format(a),end = "、")      #出现次数前5的词
  • 显然,for循环的方法更为简洁。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值