从包含python句子的字符串中查找重复字母最多的单词

我想在输入的句子中找到重复字母最多的单词。我知道如何找到句子中重复次数最多的字母,但我无法打印该单词。


例如:


这是一个基本的测试示例


应该打印


初级


def most_repeating_word(strg):

    words =strg.split()

    for words1 in words:

        dict1 = {}

        max_repeat_count = 0

        for letter in words1:

            if letter not in dict1:

                dict1[letter] = 1

            else:

                dict1[letter] += 1

            if dict1[letter]> max_repeat_count:

                max_repeat_count = dict1[letter]

                most_repeated_char = letter

                result=words1

      return result


慕桂英4014372
浏览 116回答 4
4回答

慕森王

您正在将每个单词的most_repeat_count变量重置为0。您应该将代码中的上部移动到第一个for循环的上方,如下所示:def most_repeating_word(strg):    words =strg.split()    max_repeat_count = 0    for words1 in words:        dict1 = {}        for letter in words1:            if letter not in dict1:                dict1[letter] = 1            else:                dict1[letter] += 1            if dict1[letter]> max_repeat_count:                max_repeat_count = dict1[letter]                most_repeated_char = letter                result=words1    return result

四季花海

请改用正则表达式。它简单又容易。与正则表达式相比,迭代是一项昂贵的操作。

阿晨1998

word="SBDDUKRWZHUYLRVLIPVVFYFKMSVLVEQTHRUOFHPOALGXCNLXXGUQHQVXMRGVQTBEYVEGMFD"def most_repeating_word(strg):    dict={}    max_repeat_count = 0    for word in strg:        if word not in dict:            dict[word] = 1        else:            dict[word] += 1        if dict[word]> max_repeat_count:            max_repeat_count = dict[word]    result={}    for word, value in dict.items():        if value==max_repeat_count:            result[word]=value    return resultprint(most_repeating_word(word))

慕勒3428872

有趣的练习!使用+1 Counter()。这是我的建议,还利用了max()它的key参数以及*解包运算符。对于最终解决方案,请注意,此解决方案(以及该问题的其他建议解决方案)当前不考虑大小写、其他可能的字符(数字、符号等)或是否多个单词具有最大字母数,或者如果一个单词将有多个字母且具有最大字母数。from collections import Counterdef most_repeating_word(strg):    # Create list of word tuples: (word, max_letter, max_count)    counters = [ (word, *max(Counter(word).items(), key=lambda item: item[1]))                 for word in strg.split() ]    max_word, max_letter, max_count = max(counters, key=lambda item: item[2])    return max_word
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python