Amazon Interview Question

How to count occurrences of a word in a sentence [python]

Interview Answers

Anonymous

Nov 2, 2020

text = open('data/file.txt', 'r') word_dict = {} for line in text: for word in line.split(): if word.lower() not in word_dict: word_dict[word.lower()] = 1 else: word_dict[word.lower()] += 1 for i,j in word_dict.items(): print(i + ' : ' + str(j))

4

Anonymous

Jul 20, 2020

def count_occurance(s): d= {} i =0 for words in se.split(' '): if words not in d: d[words] = i else: d[words] = i+1 return d

2

Anonymous

Apr 18, 2021

def Count_the_word(se,word): b=se.split() c=b.count(word) return c

Anonymous

Aug 12, 2020

Use Counters from Collections framework. from collection import Counter a = 'This is a sentence add add words words' count1 = Counter(a.split()) O/P: Counter({'add': 2, 'words': 2, 'This': 1, 'is': 1, 'a': 1, 'sentence': 1})

Anonymous

Jul 27, 2020

test ="Computer Science Portal" count = len (test.split()) print (count)

2