[英]Count occurences of words for each element of a list in python
I have a code which gives me count of strings in a list.我有一个代码可以计算列表中的字符串数。
names=['Deepak is a boy','Reema is short','John is tall','Deepak is shy','Munna is naughty','Reema','Deepak is shy','Amit is hilarious','John is tall','Reema is short']
nm=input('Enter the word you want to count: ')
count=names.count(nm)
print('count = ', count)
Output: Output:
Enter the word you want to count: John is tall
count = 2
However I want to find occurences of a single word for ex:shy.但是我想找到 ex:shy 出现的单个词。 If I type shy then I get count as zero.如果我输入 shy ,那么我会被计为零。 Can someone help me with how to get count of individual words.有人可以帮我计算单个单词的数量吗? Expected output for word shy:害羞一词的预期值为 output:
[0, 0, 0, 1, 0, 0, 1, 0, 0, 0]
names=['Deepak is a boy','Reema is short','John is tall','Deepak is shy','Munna is naughty','Reema','Deepak is shy','Amit is hilarious','John is tall','Reema is short']
nm=input('Enter the word you want to count: ')
occurences = [name.count(nm) for name in names]
count = sum(occurences) # This gives total number of occurences
print(occurences) # This will print out all occurences of input string
print('count = ', count) # This prints total number of occurences, although not requested may become useful for you.
This answer will allow for if names occurrences is not == 1 but greater as suggested in comments..这个答案将允许 if names occurrences is not == 1 but greater as suggested in comments..
You can loop through the list and count occurences for each text in names
.您可以遍历列表并计算names
中每个文本的出现次数。
c = []
for name in names:
c.append(name.count(nm))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.