Python实现统计给定字符串中重复模式最高子串功能示例

yipeiwu_com5年前Python基础

本文实例讲述了Python实现统计给定字符串中重复模式最高子串功能。分享给大家供大家参考,具体如下:

给定一个字符串,如何得到其中重复模式最高的子字符串,我采用的方法是使用滑窗机制,对给定的字符串切分,窗口的大小从1增加到字符串长度减1,将所有的得到的切片统计结果,在这里不考虑单个字符的重复模式,好了,很简单看具体实现:

#!usr/binenv python
#encoding:utf-8
'''''
__Author__:沂水寒城
统计一个给定字符串中重复模式数量得到最高重复模式串
'''
def slice(num_str,w):
 '''''
 对输入的字符串滑窗切片返回结果列表
 '''
 result_list=[]
 for i in range(len(num_str)-w+1):
 result_list.append(num_str[i:i+w])
 return result_list
def get_repeat_num_seq(num_str):
 '''''
 统计重复模式串数量
 '''
 result_dict={}
 result_list=[]
 for i in range(2,len(num_str)):
 one_list=slice(num_str, i)
 result_list+=one_list
 for i in range(len(result_list)):
 if result_list[i] in result_dict:
  result_dict[result_list[i]]+=1
 else:
  result_dict[result_list[i]]=1
 sorted_result_dict=sorted(result_dict.items(), key=lambda e:e[1], reverse=True)
 return sorted_result_dict[0:10]
if __name__ == '__main__':
 num_list=get_repeat_num_seq('4513785645121214545454545457894')
 print num_list

结果如下:

[('45', 8), ('4545', 5), ('454', 5), ('545', 5), ('54', 5), ('5454', 4), ('454545', 4), ('45454', 4), ('54545', 4), ('545454', 3)]
[Finished in 0.5s]

结果列表中第一个即为所求,当然,基于此还可以继续改进有很多别的需求。

PS:这里再为大家推荐2款非常方便的统计工具供大家参考使用:

在线字数统计工具:
http://tools.jb51.net/code/zishutongji

在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程

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

相关文章

教你使用python实现微信每天给女朋友说晚安

教你使用python实现微信每天给女朋友说晚安

本文为大家分享了教你用微信每天给女朋友说晚安的python实战,供大家参考,具体内容如下 但凡一件事,稍微有些重复。我就考虑怎么样用程序来实现它。 这里给各位程序员朋友分享如何每天给朋友...

python使用epoll实现服务端的方法

如下所示: #!/usr/bin/python # -*- coding: UTF-8 -*- import socket import select send_data = "h...

浅谈Python中的数据类型

数据类型: float — 浮点数可以精确到小数点后面15位 int — 整型可以无限大 bool — 非零为true,零为false list — 列表 Float/Int: 运...

Python实现图片尺寸缩放脚本

最近由于网站对图片尺寸的需要,用python写了个小脚本,方便进行图片尺寸的一些调整,特记录如下: # coding=utf-8 import Image import shut...

Python实现设置windows桌面壁纸代码分享

每天换一个壁纸,每天好心情。 # -*- coding: UTF-8 -*- from __future__ import unicode_literals import Ima...