Misty Mystery632 2023-03-08 00:32 采纳率: 25%
浏览 46
已结题

jieba词频统计中去除停用词的问题


import jieba
file_userDict = 'add_word_list.txt'
jieba.load_userdict(file_userDict)
import re
stop_file = "stopwordlist.txt"
try:
    stopword_list = open(stop_file,encoding ='utf-8')
except:
    stopword_list = []
    print("error in stop_file")
stop_list = []
for line in stopword_list:
    line = re.sub(u'\n|\\r', '', line)
    stop_list.append(line)
f=open("法律(新)\服务贸易\中华人民共和国海南自由贸易港法(FBM-CLI.1.5015177).txt","r",encoding='utf-8')
txt=f.read()
words = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) ==1:
        continue
    else:
        counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
items

我想做个先去除停用词然后对文本进行分词并词频统计的代码,然而这个代码最后得出的词频统计并没有去除停用词,请问该怎么修改呢?

  • 写回答

5条回答 默认 最新

  • 「已注销」 2023-03-08 03:31
    关注

    参考gpt和自己的思路,在代码中,你已经成功读取并生成了停用词列表stop_list,可以在统计词频时添加一个判断,如果单词出现在停用词列表中,则不加入词频统计。下面是修改后的代码:

    
    import jieba
    import re
    
    file_userDict = 'add_word_list.txt'
    jieba.load_userdict(file_userDict)
    
    stop_file = "stopwordlist.txt"
    try:
    stopword_list = open(stop_file, encoding='utf-8')
    except:
    stopword_list = []
    print("error in stop_file")
    stop_list = []
    for line in stopword_list:
    line = re.sub(u'\n|\r', '', line)
    stop_list.append(line)
    
    f = open("法律(新)\服务贸易\中华人民共和国海南自由贸易港法(FBM-CLI.1.5015177).txt", "r", encoding='utf-8')
    txt = f.read()
    words = jieba.lcut(txt)
    counts = {}
    for word in words:
    if len(word) == 1 or word in stop_list: # 判断单词长度是否为1或者是否出现在停用词列表中
    continue
    else:
    counts[word] = counts.get(word, 0) + 1
    items = list(counts.items())
    items.sort(key=lambda x: x[1], reverse=True)
    print(items) # 输出词频统计结果
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 3月16日
  • 已采纳回答 3月8日
  • 赞助了问题酬金15元 3月8日
  • 创建了问题 3月8日

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂