[英]How do i get count of consonants
我必須計算給定字符串中存在的輔音,但似乎缺少一些東西。 我需要修改什么以獲得預期的結果
我的代碼:
var = 'aaeouAIyuiodffgXUEEE'
vowels='aeiou'
for i in vowels:
if i is not var:
print(var)
預期結果:
y 1
d 1
f 2
g 1
x 1
您可以使用collections.Counter
來完成這項工作。 這是一個dict
子類,其中每個元素都存儲為字典鍵,它們的計數存儲為字典值。 因此,您可以訪問以下計數:
>>> counts['y']
1
然后對鍵值對的元組使用sorted
function 以按字母順序對字母進行排序,並使用dict
構造函數重新構造字典。
from collections import Counter
var = 'aaeouAIyuiodffgXUEEE'
vowels='aeiou'
counts = Counter([x for x in var.lower() if x not in vowels])
counts = dict(sorted(counts.items()))
Output:
{'d': 1, 'f': 2, 'g': 1, 'x': 1, 'y': 1}
您可以通過以下方式找到所有輔音的總和:
total = sum(counts.values())
Output:
6
您應該使用迭代器i
逐個字符地瀏覽整個字符串var
,並檢查每個字符是否為常量(或不是)。 使用vowels
字符串非常有用,您應該檢查其中的至少一個字符是否等於i
。 Python 已經有一個 function 。
像這樣的東西:
for i in var:
if i not in vowels:
# increase the consonant counter
如何增加輔音計數器? 好吧,您可以使用以輔音作為鍵的字典。 例如:
cons = {'b': 0, 'c': 0, ...}
不要忘記首先將所有值設置為 0。 您還可以使用for
循環創建字典(如果您想更快更高效地執行此操作)。
現在,只要你找到一個輔音,就做cons[i] = cons[i]+1
。 最后,遍歷字典和 output 每個鍵及其值。
如果您不想將空格視為輔音,則可以使用collections. Counter
與str. isalpha()
一起collections. Counter
。 str. isalpha()
:
from collections import Counter
def get_consonant_counts(s: str) -> dict[str, int]:
"""Returns counts of consonants in string ignoring case."""
return dict(
Counter(c for c in s.lower() if c.isalpha() and c not in set('aeiou')))
var = 'aaeouAIyuiodffgXUEEE'
var_consonant_counts = get_consonant_counts(s=var)
for consonant, count in var_consonant_counts.items():
print(f'{consonant} {count}')
total_consonants = sum(var_consonant_counts.values())
print(f'{total_consonants = }')
Output:
y 1
d 1
f 2
g 1
x 1
total_consonants = 6
試試上面的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.