zoukankan      html  css  js  c++  java
  • Python统计字符出现次数(Counter包)以及txt文件写入

    # -*- coding: utf-8 -*-
    #spyder (python 3.7)

    1. 统计字符(可以在jieba分词之后使用)

    from collections import Counter
    from operator import itemgetter
    
    # txt_list可以写成函数参数进行导入
    txt_list = ['千古','人间','人间','','','','哈哈哈','人才','千古','千古']
    c = Counter()
    for x in txt_list:
        if len(x) >= 1:
            if x == '
    ' or x == '
    ' or x == ' ':
                continue
            else:
                c[x] += 1
    print('常用词频统计结果: 
    ')
    for (k, v) in c.most_common(4): #打印排名前四位
        print('%s%s %s  %d' % ('  ' * (3 ), k, '*' * 3, v))
    
    # 按照词频数从大到小打印
    d = sorted(c.items(),key=itemgetter(1),reverse = True)
    for ss,tt in d:
        out_words=ss + '	' + str(tt)
        print(out_words)

    2. 多次覆盖,循环写入文件

    #写入文件,多次写入,后一次覆盖前一次,但是out_words本身是在叠加的
    #即:第一次写入的是:千古	3
    ;第二次写入的是:千古	3
    龙	3
    ,覆盖上一次的数据;
    #第三次是:千古	3
    龙	3
    人间	2
    ,继续覆盖上一次的数据
    out_words = ''
    for ss,tt in d:
        out_words=out_words + ss + '	' + str(tt) + '
    '
        with open(r".sss.txt", "w",encoding='utf-8') as f:
            f.write(out_words+'
    ')

    比如,循环两次的结果是:

     3. 一次性写入文件,中间不会覆盖和多次写入;但是如果重复运行代码,则会覆盖之前的全部内容,一次性重新写入所有新内容

    out_words = ''
    for ss,tt in d:
        out_words=out_words + ss + '	' + str(tt) + '
    '
    with open(r".	tt.txt", "w",encoding='utf-8') as f:
            f.write(out_words+'
    ')

  • 相关阅读:
    移动端rem适配
    extern 关键字
    腾讯2014校园招聘软件开发类笔试试题
    堆,栈,堆栈
    转:对TCP/IP网络协议的深入浅出归纳
    转:程序员面试笔试宝典学习记录(一)
    求素数
    [C++]访问控制与继承(public,protect,private) 有时间再整理!!!
    面向对象的static关键字(类中的static关键字)
    腾讯校园招聘会笔试题2011.10.15
  • 原文地址:https://www.cnblogs.com/qi-yuan-008/p/11688911.html
Copyright © 2011-2022 走看看