Python | 查找字符串中每个字符的频率
Given a string and we have to find the frequency of each character of the string in Python.
給定一個字符串,我們必須在Python中查找該字符串的每個字符的頻率。
Example:
例:
Input: "hello"Output:{'o': 1, 'h': 1, 'e': 1, 'l': 2}Python code to find frequency of the characters
Python代碼查找字符頻率
# Python program to find the frequency of # each character in a string# function definition # it accepts a string and returns a dictionary # which contains the frequency of each chacater def frequency(text):# converting string to lowercasetext = text.lower()# dictionary declarationdict = {}# traversing the charactersfor char in text:keys = dict.keys()if char in keys:dict[char] += 1else:dict[char] = 1return dict# main code if __name__ == '__main__':# inputting the string and printing the frequency# of all charactersuser_input = str(input("Enter a string: "))print(frequency(user_input))user_input = str(input("Enter another string: "))print(frequency(user_input))Output
輸出量
Enter a string: Hello {'o': 1, 'h': 1, 'e': 1, 'l': 2} Enter another string: aabbcc bb ee dd {'a': 2, 'd': 2, 'e': 2, 'b': 4, 'c': 2, ' ': 3}Explanation:
說明:
In the above example main () function execute first then it'll ask the user to enter the string as input. After that frequency() will be called. user_input contains the string entered by the user. user_input is now passed through the function. The function turns all the characters into the lowercase after that using for loop the frequencies of all the characters will be counted. And then, an empty dictionary will be created where characters will be stored as the values of the characters and frequencies will be stored as the keys of the dictionary.
在上面的示例中,main()函數首先執行,然后要求用戶輸入字符串作為輸入。 之后, frequency()將被調用。 user_input包含用戶輸入的字符串。 現在, user_input通過函數傳遞。 在使用for循環之后,該功能會將所有字符轉換為小寫字母,然后將對所有字符的頻率進行計數。 然后,將創建一個空字典,在其中將字符存儲為字符的值,而頻率將存儲為字典的鍵。
翻譯自: https://www.includehelp.com/python/find-the-frequency-of-each-character-in-a-string.aspx
總結
以上是生活随笔為你收集整理的Python | 查找字符串中每个字符的频率的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言给定一个非空整数数组_C程序检查给
- 下一篇: 基于Python的应用程序的虚拟环境