简体   繁体   中英

Python - How to count characters, but only print once?

I am trying to figure out my code. The objective of the code is to create a character frequency counter. The character frequency counter must display the result in alphabetical order. So, the code must take input and display the number of characters like this:

input = ("apple") 'a' = 1

'e' = 1

'l' = 1

'p' = 2

Currently, my code does this:

'a' = 1

'e' = 1

'l' = 1

'p' = 2

'p' = 2

Any ideas for solving this problem? Ideally, I would only want 'p' to be displayed once, but count both characters.

Here is my code:

char_dict = {}
user_input = input("Please enter a word or sentence: ")
user_input = user_input.replace(" ", "")
user_input = user_input.lower()
test_list = list(user_input)
test_list.sort()
for character in user_input:
    char_dict[character] = 0
for character in user_input:
    char_dict[character] = char_dict[character] + 1
for character in test_list:
    print (character, ":", char_dict[character])

Any help is appreciated greatly. Thank you so much!

You have all right parts and pieces but the problem is actually simpler than you're making it:

user_input = input("Please enter a word or sentence: ")
user_input = user_input.replace(" ", "")
user_input = user_input.lower()

char_dict = {}

for character in user_input:
    char_dict[character] = char_dict.get(character, 0) + 1

for character in sorted(char_dict):
    print(character, ":", char_dict[character])

OUTPUT

> python3 test.py
Please enter a word or sentence: apple
a : 1
e : 1
l : 1
p : 2
>

You can try this one too:

string = "apple" #Input string
string = string.replace(" ","").lower() #In case of whitespace
setString = sorted(map(lambda i : [i,string.count(i)], set(string)))
for i in setString:
    print("%s : %d" % (i[0],i[1]))

Output:

a : 1
e : 1
l : 1
p : 2

This is how I would write your program, using collections.Counter and the new-fangled f-strings :

from collections import Counter
word = input("What is your word? ")
letter_counts = Counter(word.lower())
sorted_letter_counts = sorted(letter_counts.items())
for letter, count in sorted_letter_counts:
    print(f"'{letter}' = {count}")

Maybe you can create some list of 'used symbols' and after you count any symbol, just add it to list.

usedsymb=[]
for character in user_input:
    if usedsymb.count(character)==0:
        char_dict[character] +=1        (this will add 1)
        usedsymb.append(character)

You get 'p' twice because you are looping across the word 'apple' which has 'p' in it twice. Try looping across the sorted list of keys in your dictionary as that will only ever have one unique key for each character.

So changing the 2nd to last line, and removing a couple of no longer needed lines :

char_dict = {}
user_input = input("Please enter a word or sentence: ")
user_input = user_input.replace(" ", "")
user_input = user_input.lower()

for character in user_input:
    char_dict[character] = 0
for character in user_input:
    char_dict[character] = char_dict[character] + 1
for character in sorted(char_dict.keys()):
    print (character, ":", char_dict[character])

The one better solution I could think of is using the collections package in Python. It is a design pattern. The collection package has a method Counter which will give solution to your problem.

It is pretty simple and easy to use.

Following is the code block for that.

input_string = "apple" from collections import Counter result = Counter([i for i in input_string]) print (result)

This should do the magic trick for you. It is often better to use the design patterns because they will ease the work.

Using counter, you get your desired result in very few lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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