📜  Python – 不区分大小写的字符串计数器

📅  最后修改于: 2022-05-13 01:54:31.157000             🧑  作者: Mango

Python – 不区分大小写的字符串计数器

给定一个字符串列表,找出不区分大小写的字符串的频率。

方法:使用 defaultdict() + lower()

在此,我们在映射到 defaultdict 之前对所有字符串执行 lower()。这确保了在映射和累积频率时不区分大小写。

Python3
# Python3 code to demonstrate working of 
# Strings Frequency (Case Insensitive)
# Using defaultdict() + lower()
from collections import defaultdict
  
# initializing list
test_list = ["Gfg", "Best", "best", "gfg", "GFG", "is", "IS", "BEST"]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = defaultdict(int)
for ele in test_list:
      
    # lowercasing to cater for Case Insensitivity
    res[ele.lower()] += 1
  
# printing result 
print("Strings Frequency : " + str(dict(res)))


输出
The original list is : ['Gfg', 'Best', 'best', 'gfg', 'GFG', 'is', 'IS', 'BEST']
Strings Frequency : {'gfg': 3, 'best': 3, 'is': 2}