Get Frequency of Characters in Python
def main():
"""
Counts the frequency of all vowels in a string.
"""
txt = input("Enter string: ")
a = 0
e = 0
i = 0
o = 0
u = 0
for c in txt:
match c:
case "A" | "a":
a += 1
case "E" | "e":
e += 1
case "I" | "i":
i += 1
case "O" | "o":
o += 1
case "U" | "u":
u += 1
case _:
pass
print(f"A/a: {a}")
print(f"E/e: {e}")
print(f"I/i: {i}")
print(f"O/o: {o}")
print(f"U/u: {u}")
if __name__ == "__main__":
main()
def main():
"""
Prints the number of occurrences of each English letter in a string.
"""
text = input("Enter string: ")
counts = frequency(text)
for i in range(26):
if counts[i] > 0:
print(chr(i + ord("a")) + ": " + str(counts[i]))
def frequency(text: str):
"""
Counts the frequency of English letter in a string.
"""
# Represent the frequency of 26 English letters in an array
counts = [0] * 26
# Count the occurrences of each lower cased English letter
for c in text:
c = c.lower()
if "a" <= c < "a":
counts[ord(c) - ord("a")] += 1
return counts
if __name__ == "__main__":
main()
def main():
text = input("Enter string: ")
counts = frequency(text)
print(counts)
def frequency(text: str):
counts = {}
for c in text:
if c.isspace():
continue
# Increment count if character already exists, else start at 1
counts[c] = counts.get(c, 0) + 1
# Sort by character (like TreeMap in Java)
return dict(sorted(counts.items()))
if __name__ == "__main__":
main()
from collections import Counter
def main():
text = input("Enter string: ")
counts = frequency(text)
print(counts)
def frequency(text: str):
# Remove whitespace and count characters
filtered = [c for c in text if not c.isspace()]
counts = Counter(filtered)
# Return a dictionary sorted by character
return dict(sorted(counts.items()))
if __name__ == "__main__":
main()