简体   繁体   English

Python-如何计算字符,但只能打印一次?

[英]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 输入=(“苹果”)'a'= 1

'e' = 1 'e'= 1

'l' = 1 'l'= 1

'p' = 2 'p'= 2

Currently, my code does this: 目前,我的代码执行此操作:

'a' = 1 'a'= 1

'e' = 1 'e'= 1

'l' = 1 'l'= 1

'p' = 2 'p'= 2

'p' = 2 'p'= 2

Any ideas for solving this problem? 有解决这个问题的想法吗? Ideally, I would only want 'p' to be displayed once, but count both characters. 理想情况下,我只希望将“ p”显示一次,但同时计算两个字符。

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 : 这就是我使用collections.Counter和新的f字符串编写程序的方式:

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. 您会两次获得“ p”,因为您要遍历其中有“ p”的单词“ apple”。 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. 我能想到的一个更好的解决方案是在Python中使用collections包。 It is a design pattern. 这是一种设计模式。 The collection package has a method Counter which will give solution to your problem. 收集包中有一个Counter方法,该方法可以解决您的问题。

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. 使用计数器,只需几行代码即可获得所需的结果。

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

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