网络编程
位置:首页>> 网络编程>> Python编程>> Python实现统计给定字符串中重复模式最高子串功能示例

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

作者:Together_CZ  发布时间:2023-07-22 23:42:44 

标签: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程序设计有所帮助。

来源:https://blog.csdn.net/together_cz/article/details/74761447

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com