编写一个程序,让用户输入一个字符串,并显示字符串中最常出现的字符

时间:2016-11-16 16:28:33

标签: python string lines

我目前正在研究python,我对此并不了解。在词典之前,我正在寻找这个问题的帮助。这个问题是在没有任何词典的情况下完成的。问题是我对max函数了解不多。

我到目前为止:

AlphaCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

for ch in text: 
   ch = ch.upper()
   index=Alpha.find(ch)

   if index >-1:
       AlphaCount[index] = AlphaCount[index]+1

3 个答案:

答案 0 :(得分:1)

您可以使用计数器

from collections import Counter
foo = 'wubalubadubdub'
Counter(list(foo))

获得最常见的信件

Counter(list(foo)).most_common(1)

答案 1 :(得分:0)

您可以使用set来获取输入中唯一的字符。然后迭代它们并计算在count输入中出现的次数。如果更频繁地出现,那么最大值和isalpha(不是空格)则将max设置为计数。

text='This is a test of tons of tall tales'
un=set(text.upper())
max=0
fav=''

for u in un:
    c=text.upper().count(u)
    if c>max and u.isalpha():
        max=c
        fav=u
print(fav) # T
print(max) # 6

修改

要从您的代码执行此操作:修复大写(for,if),然后查找并打印/返回最常用的字母。另外AlphaCount有一个额外的0,你只需要26。

text='This is a test of tons of tall talez'
AlphaCount=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'

for ch in text: 
    ch= ch.upper()
    index=Alpha.find(ch)

    if index >-1:
        AlphaCount[index]+=1
print(AlphaCount) # the count of characters
print(max(AlphaCount)) # max value in list
print(AlphaCount.index(max(AlphaCount))) # index of max value
print(Alpha[AlphaCount.index(max(AlphaCount))]) # letter that occurs most frequently

答案 2 :(得分:0)

def main():

    string = input('Enter a sentence: ')

    strings=string.lower()

    counter = 0
    total_counter = 0

    most_frequent_character = ""

    for ch in strings:
        for str in strings:
            if str == ch:

                counter += 1
        if counter > total_counter:
            total_counter = counter
            most_frequent_character = ch
        counter = 0

    print("The most frequent character is", most_frequent_character, "and it appears", total_counter, "times.")

main()