本文实例讲述了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程序设计有所帮助。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月27日
2024年09月27日
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CUE】
- 赞多《序章》[FLAC/分轨][129.13MB]
- 群星《完美的她 影视原声带》[320K/MP3][51.98MB]
- 群星《完美的她 影视原声带》[FLAC/分轨][141.05MB]
- 山风点伙.1997-深藏不露【立得】【WAV+CUE】
- 李幸倪.2018-First.Of.All.Live.Concert.3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CUE】
- 群星《你就在我身边 电影原声专辑》[320K/MP3][26.68MB]
- 群星《你就在我身边 电影原声专辑》[FLAC/分轨][70.27MB]
- 班得瑞原装进口《20周年精选集》1CD[APE/CUE分轨][303MB]
- 群星.2009-NOON.D.广东.2CD【新世纪】【WAV+CUE】
- 洪卓立.2012-GROWN.UP【英皇娱乐】【WAV+CUE】
- 梁静茹.2007-崇拜【相信音乐】【WAV+CUE】
- 金佩姗.1997-喜新恋旧【现代派】【WAV+CUE】
- 梁静茹.2007-崇拜【相信音乐】【WAV+CUE】