-3

In line,

Boys dance, girls dance, he dances, she dances

how to count the number of times dance occurs without counting the number of times dances occurs (using a Python program)?

A method is

>>> var = "Boys dance, girls dance, he dances, she dances"
>>> count1 = var.count("dance")
>>> count2 = var.count("dances")
>>> count = count1 - count2
>>> count
2
>>>

But it is too lengthy.

Is any one line method available?

puregeek
  • 175
  • 3
  • 9

4 Answers4

3

This will simply count the number of times the expression "dance" appears

import re
print len(re.findall('dance\\b', string))

This website should give you more information about the regular expression lib. https://docs.python.org/2/library/re.html

Bryce Ramgovind
  • 3,127
  • 10
  • 41
  • 72
3

Try below

import re
count = sum(1 for _ in re.finditer('(dance[^\\w])', line))
print(count)
johnII
  • 1,423
  • 1
  • 14
  • 20
2

One option is to use Regular Expressions:

import re
len(re.findall("dance[^s]", string))
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
1

With list comprehension: Split at " ", strip ",." from splits

v = "Boys dance, girls dance, he dances, she dances"
print(len([x for x in v.split() if x.strip(".,") == "dance"]))

The answers in Finding occurrences of a word in a string in python 3 using list comprehensions do not deal with punktioations glued to the split words - so decided to answer here as well.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69