日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python | 查找字符串中每个字符的频率

發布時間:2025/3/11 python 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 | 查找字符串中每个字符的频率的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。