python获取指定字符串中重复模式最高的字符串方法
作者:Together_CZ 时间:2021-03-25 14:59:25
给定一个字符串,如何得到其中重复模式最高的子字符串,我采用的方法是使用滑窗机制,对给定的字符串切分,窗口的大小从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]
结果列表中第一个即为所求,当然,基于此还可以继续改进有很多别的需求。
来源:https://blog.csdn.net/Together_CZ/article/details/74761447
标签:python,重复,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp是的日期转换为星座的函数
2011-02-26 11:11:00
Python探索之修改Python搜索路径
2021-06-26 20:47:09
PHP实现手机号码中间四位用星号(*)隐藏的自定义函数分享
2023-11-06 06:36:22
SQL Server数据库对于应用程序的关系
2010-09-08 09:42:00
python PyTorch参数初始化和Finetune
2023-04-26 08:53:44
![](https://img.aspxhome.com/file/2023/4/75934_0s.png)
Oracle 语句优化分析说明第1/2页
2009-09-18 13:23:00
php函数serialize()与unserialize()用法实例
2023-11-19 00:53:23
一篇教程教你学会Python进制转换(十进制转二进制、八进制、十六进制)
2022-10-04 06:56:04
![](https://img.aspxhome.com/file/2023/7/72747_0s.png)
带中英文翻译功能的收藏夹
2008-07-31 11:33:00
Golang 的defer执行规则说明
2023-07-14 08:31:10
Oracle DBA常用语句
2009-08-05 20:15:00
Sql Server 2012 转换函数的比较(Cast、Convert和Parse)
2012-08-21 10:21:40
妄想or未来?界面的虚拟现实化
2010-03-01 12:53:00
![](https://img.aspxhome.com/file/UploadPic/20103/1/1002-gui-virtual-01-22s.jpg)
php 参数过滤、数据过滤详解
2023-11-17 17:36:56
js图片随机显示技巧
2007-08-19 20:20:00
PHP+Mysql基于事务处理实现转账功能的方法
2023-10-21 16:53:06
13个你希望早点知道的实用WordPress SQL查询语句[译]
2010-02-28 12:48:00
![](https://img.aspxhome.com/file/UploadPic/20102/28/sqlbox-14s.jpg)
laravel的用户修改密码与绑定邮箱的详细操作
2023-06-17 09:55:06
![](https://img.aspxhome.com/file/2023/5/55535_0s.jpg)
如何在ACCESS中插入超级链接?
2007-10-22 12:13:00
![](https://img.aspxhome.com/file/UploadPic/200710/22/2007102212225806s.gif)
asp截取字符串的两种应用
2009-08-19 17:11:00