petit_herisson

导航

Exercise: Week 3-3.1-1

Enter an English sentence. Except for words and spaces, the sentence contains only punctuation ",", ".", "'", "", and "!".

Count the times of each word in the sentence (convert the uppercase of the sentence to lowercase) and store the result in a dictionary and output.

sentence = input("Enter a sentence: ").lower()

def check():
  # check if the sentence is corret pun
= (",", ".", "'", "", "!") list_check = list(sentence) for l in list_check: if l.isalpha() != True: if l not in pun: print("Invalid enter!") again = input("Enter a sentence: ") else: return sentence check() lst = sentence.split(" ") keys = [] for item in lst: for i in item: if i.isalpha() != True: keys.append(i) item = item.strip(i) keys.append(item) keys_set = set(keys) dic = dict.fromkeys(keys_set, int(0)) for key in keys: dic[key] += 1 for k, v in dic.items(): print(k, v)

 

[Reference Code]

 

s = input("enter an English sentence: ")
s = s.lower()
sList = s.split()
sDict = {}
for item in sList:    
    if item[-1] in ',.\'"!':
        item = item[:-1]
    if item not in sDict:
        # the word frequency is 1 if the word is appeare first time
        sDict[item] = 1 
    else:
        # words encountered after the second or later are accumulated 1 in the original word frequency
        sDict[item] += 1 
print(sDict)

# the if-else statement in the above program is often replaced by the following statement

# sDict[item] = sDict.get(item, 0) + 1

 

22:48:38

2019-11-27

posted on 2019-11-27 17:49  petit_herisson  阅读(112)  评论(0)    收藏  举报