zoukankan      html  css  js  c++  java
  • 【Python】文本包jieba使用

    看了一个教程:https://www.cnblogs.com/wkfvawl/p/9487165.html
    有些不懂的地方自己查阅了一下

    1. 键值的添加,获得文件中相同字符出现的次数, counts = {},counts.get(word,0)
      一个常用的统计词频的方法
    txt = "a b c d a b c a b a e"
    words = txt.split() #将每个字符按空格分开
    print(words) #输出示例
    counts = {}  #新建一个字典
    for word in words:
        counts[word] = counts.get(word,0) + 1 #能够获得键对应的值
        print(list(counts.items()))
    
    1. Python Dictionary items()方法
      字典的一个函数,以列表返回可遍历的(键,值)元组元素
    s = "双儿 洪七公 赵敏 赵敏 逍遥子 鳌拜 殷天正 金轮法王 乔峰" 
    ls=s.split()
    counts={}
    for word in ls:
        counts[word]=counts.get(word,0)+1
    item=counts.items()
    print("字典类型:",counts)
    print("元组类型:",item)
    

    出来的结果不是list类型,需要强制转化为list类型。

    1. 元素排序:items.sort[key=lambda x:x[1],reverse=True)
      key=lambda x: x[1]lambda是一个隐函数,在这里可以不用管它,记得有这个就可以
      后面的x: x[1] 为对前面的对象中的第二维数据(即value)的值进行排序。

    2. 格式化输出print("{0:<5}{1:>5}".format(word, count))
      print ("{0:<10}{1:>5}".format(word, count))
      这个是format方法的格式控制。

    {<参数序号>:<填充符号><对齐><宽度><,>< . 精度 ><类型>}
    < : 左对齐
    > :右对齐
    ^ : 居中对
    < , > 表示数字的千位分隔符
    整数类型:b, c, d, o, x, X
    浮点数类型:e, E, f, %
    
    >>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
    'hello world'
     
    >>> "{0} {1}".format("hello", "world")  # 设置指定位置
    'hello world'
     
    >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
    'world hello world'
    
    import jieba
    txt = open("三国演义.txt", "r", encoding='utf-8').read()
    words = jieba.lcut(txt)
    counts = {} #通过键值对的形式存储词语及其出现次数
    
    for word in words:
        if len(word) == 1:
            continue
        else:
            counts[word] = counts.get(word, 0) + 1 #有word时返回其值,+1能够累计次数
    #参考https://blog.csdn.net/weixin_42800007/article/details/82024108 
    
    items = list(counts.items())
    print(type(items[5]))
    items.sort(key = lambda x: x[1], reverse = True)
    #key = lambda隐函数;x:x[1]按第二维数据排序(value)
    
    for i in range(15):
        word, count = items[i]
        print("{0:<5}{1:>5}".format(word, count))
    
    
  • 相关阅读:
    vmware虚拟机 安装
    js中设置元素class的三种方法小结
    HTML可编辑的select
    视图和表的区别和联系
    数据库之常用函数
    数据库之Group By用法
    数据库之存储过程
    数据库内外连接讲解
    ExtJs知识点概述
    SpringMVC 400 Bad Request 问题
  • 原文地址:https://www.cnblogs.com/kinologic/p/14853799.html
Copyright © 2011-2022 走看看