avp26/u4/word_count.py
2026-10-06 12:44:50 +02:00

31 lines
849 B
Python

from collections import defaultdict
def count_words(sentance: str) -> dict:
sent_list = list(sentance)
words = defaultdict(int)
SPECIAL_CHAR = oct(7)
delims = ":?!\n\t,._&@$^&*()%"
del_chars = '"'
forbidden = list(delims) + list(del_chars) + [" ", "'", ""]
for i, ch in enumerate(sent_list):
if(ch in delims):
sent_list[i] = " "
elif(ch in del_chars):
sent_list[i] = ""
if(ch == "'"):
if((sent_list[max(i-1, 0)] not in forbidden) and (sent_list[min(i+1, len(sent_list)-1)] not in forbidden)):
sent_list[i] = SPECIAL_CHAR
else:
sent_list[i] = ""
for w in ''.join(sent_list).lower().split(" "):
if w == "":
continue
words[w.replace(SPECIAL_CHAR, "'")] += 1
return dict(words)