当前位置:   article > 正文

用python对字符串分词,并计算词数_python分词词语个数

python分词词语个数
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 11:29:53 2020

@author: weisssun
"""

import jieba
import csv
import pandas as pd

jieba.load_userdict(r"D:\Python\dict\userdict.txt")
#加载用户词典
    
input_path = r'D:\Python\data\评论.xlsx'
#原始数据路径

outpath = r'D:\Python\data\评论-词数.csv'
#输出数据路径

results = []
#将结果保存在results列表中,写入csv文件

raw_data = pd.read_excel(input_path, encoding = 'utf-8')
#读取原始数据
for comment in raw_data.comment.astype(str):
    #读取原始数据中的文本列,并将其转换为字符串格式
    #否则jieba会报错
    cut_words=[]
    result = []
    #print(comment)
    seg_list = jieba.cut(comment,cut_all=False)
    #调用jieba分词
    for i in seg_list:
        cut_words.append(i)
    #将分词结果保存为列表
    #print(cut_words)
    #print(len(cut_words))
    #word_freq.append(len(cut_words))
    result.append(comment)
    result.append(cut_words)
    result.append(len(cut_words))
    #将原始评论、分词结果、词数保存在列表result中
    results.append(result)
    #将所有result保存在列表results中
#print(results)


with open(outpath, 'w', newline='',encoding='gbk') as f:
    writer = csv.writer(f)            
    for result in results:
        writer.writerow(result)
    #将结果写入csv文件,每个result是一行
  • 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
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号