python统计一个文本中重复行数的方法

作者:shichen2014 时间:2021-08-20 12:50:46 

本文实例讲述了python统计一个文本中重复行数的方法。分享给大家供大家参考。具体实现方法如下:

比如有下面一个文件
2
3
1
2
我们期望得到
2,2
3,1
1,1

解决问题的思路:

出现的文本作为key, 出现的数目作为value,然后按照value排除后输出
最好按照value从大到小输出出来,可以参照:

in recent Python 2.7, we have new OrderedDict type, which remembers the order in which the items were added.
>>> d = {"third": 3, "first": 1, "fourth": 4, "second": 2}
>>> for k, v in d.items():
...     print "%s: %s" % (k, v)
...
second: 2
fourth: 4
third: 3
first: 1
>>> d
{'second': 2, 'fourth': 4, 'third': 3, 'first': 1}To make a new ordered dictionary from the original, sorting by the values:
>>> from collections import OrderedDict
>>> d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))The OrderedDict behaves like a normal dict:
>>> for k, v in d_sorted_by_value.items():
...     print "%s: %s" % (k, v)
...
first: 1
second: 2
third: 3
fourth: 4
>>> d_sorted_by_value
OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)])


代码如下:

#coding=utf-8
import operator
f = open("f.txt")
count_dict = {}
for line in f.readlines():
    line = line.strip()
    count = count_dict.setdefault(line, 0)
    count += 1
    count_dict[line] = count
sorted_count_dict = sorted(count_dict.iteritems(), key=operator.itemgetter(1), reverse=True)
for item in sorted_count_dict:
    print "%s,%d" % (item[0], item[1])

补充说明:
1. python的dict对象的两个方法:

items方法将所有的字典项以列表的方式返回, 这些列表项中每一项都来自于(键, 值)
iteritems方法与items的作用大致相同, 但是返回一个迭代器对象而不是列表

2. python的内建函数sorted

>>> help(sorted)
Help on built-in function sorted in module __builtin__:
sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

希望本文所述对大家的Python程序设计有所帮助。

标签:python,统计,文本
0
投稿

猜你喜欢

  • python中日期和时间格式化输出的方法小结

    2023-07-01 11:39:31
  • Python实现用手机监控远程控制电脑的方法

    2021-06-22 07:57:49
  • Django2.1.3 中间件使用详解

    2023-11-06 19:46:00
  • 教你精确编写高质量高性能的MySQL语法

    2009-01-14 12:57:00
  • 解决python3捕获cx_oracle抛出的异常错误问题

    2023-01-21 17:51:26
  • 如何把数组转换成字符串?

    2009-11-06 13:49:00
  • Python面向对象实现方法总结

    2022-03-11 08:50:41
  • PHP二维码的生成与识别案例

    2023-06-14 06:48:55
  • Python+Opencv实现计算闭合区域面积

    2023-03-17 03:02:44
  • PHP中trait的使用和同时引入多个trait时同名方法冲突的处理方法

    2023-06-16 23:13:52
  • Python不使用int()函数把字符串转换为数字的方法

    2022-04-22 02:32:33
  • 跨浏览器实现float:center,No CSS hacks

    2008-08-22 12:59:00
  • OpenCV实现车辆识别和运动目标检测

    2023-09-22 18:55:40
  • 用Css来制作一个漂亮的多选列表框

    2008-05-29 12:45:00
  • ASP制作中使用MYSQL的分析

    2008-10-13 09:25:00
  • Python3实现的反转单链表算法示例

    2021-09-22 01:33:30
  • Python执行外部命令subprocess的使用详解

    2023-01-21 14:57:49
  • Django调用百度AI接口实现人脸注册登录代码实例

    2023-10-13 23:07:14
  • CSS绝对定位在宽屏分辨率下错位

    2009-07-28 12:24:00
  • 详解Python中while无限迭代循环方法

    2022-08-17 12:53:48
  • asp之家 网络编程 m.aspxhome.com