简体   繁体   English

如何计算 Python 列表项中单词的连续最大出现次数

[英]How to count Consecutive Maximum Occurrence of a word in an item of a list in Python

I'm trying to implement a code that will count the longest run of a word in an item of a list我正在尝试实现一个代码,该代码将计算列表项中单词的最长运行时间

    for_example = ['smaplakidfsmapsmapsmapuarebeautiful']

so in this example, it will be 3 because smap was repeated 3 times so is there is a code that does this task for me no matter what the word is.所以在这个例子中,它将是 3,因为 smap 重复了 3 次,所以无论单词是什么,都有一个代码可以为我完成这项任务。

EDIT: If you have a list of items, you can call the function like this:编辑:如果你有一个项目列表,你可以像这样调用 function:

[countMaxConsecutiveOccurences(item, 'smap') for item in items]
def countMaxConsecutiveOccurences(item, s):
    i = 0
    n = len(s)
    current_count = 0
    max_count = 0
    while i < len(item):
        if item[i:i+n] == s:
            current_count += 1
            max_count = max(max_count, current_count)
            i += n
        else:
            i += 1
            current_count = 0     
    return max_count

countMaxConsecutiveOccurences('smaplakidfsmapsmapsmapuarebeautiful', 'smap')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM