简体   繁体   English

如何用Python中的边缘格计数特定单词的出现

[英]How to count the occurrence of a particular word with edge cases in Python

I have written the code to count the occurrence of a certain word cat in it, the code is passing only some of my test cases, it is not passing all the test, especially the edge cases. 我已经编写了代码来计算其中某个单词cat的出现,该代码仅通过了我的一些测试用例,而没有通过所有测试,尤其是边缘情况。 Please note am not allowed to use inbuilt functions like count() and a whole host of others. 请注意,不允许使用诸如count()之类的内置函数以及大量其他函数。 Here is my code: 这是我的代码:

mystery_string = "my cat your cat"
splitword = mystery_string.split()
sum = 0
for string in splitword:
    if string == "cat":
        sum += 1
print (sum)

when i change the variable mystery_string to mystery_string = "catcatcatcatcat!!". 当我将变量mystery_string更改为mystery_string = "catcatcatcatcat!!". or mystery_string = "cacacat cacacat" or this one mystery_string = "ucatX" or even this mystery_string = ".$cacacatcatcat". mystery_string = "cacacat cacacat"或此mystery_string = "ucatX"甚至此mystery_string = ".$cacacatcatcat". the code just breaks. 该代码只是打破。 i have researched stackoverflow for similar problem but no solution. 我已经研究了stackoverflow的类似问题,但没有解决方案。

Use the count method of strings. 使用字符串的计数方法。

>>> "catcatcatcatcat!!".count("cat")
5

Or, using regular expressions : 或者,使用正则表达式

>>> import re
>>> len(re.findall("cat", "catcatcatcatcat!!"))
5

Actually there is the ".count(str)" function Ex: 实际上有一个“ .count(str)”函数,例如:

catcatcat!ccat".count("cat")

Outputs 4 But if you don't want to use it you can do the following 输出4但是,如果您不想使用它,可以执行以下操作

def count(mainstr, substr):
 thecount = 0
 for i in range(len(mainstr)):
  if i <= len(mainstr) - len(substr):
   if mainstr[i:i+len(substr)] == substr:
    thecount+=1
 return thecount

Your code counts the occurrence of a word in a text but not the occurrence of a word in a string... 您的代码会计算文本中单词的出现次数,而不计算字符串中单词的出现次数...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM