Search word with exactness

2

Good people I have a small text of 1859 words where I stored it all in a variable in the format string. The question and the following I have this little code I made below:

w = wordstring.split()
i = 0
for x in w:
    c = x.find('Be')
    if c == 0:
        i += 1
        print('{} - {}'.format(i, x))

I want to search for the exact word that in the case would be 'Be', but in my output it does not return with this precision:

1 - Being
2 - Besides,
3 - Be
4 - Before,

Is there any pythonic way for me to have this exactness.

    
asked by anonymous 11.08.2017 / 15:36

1 answer

2

Code:

import re

text = "be besides being bee be, be. before, Be Be. forbe be_ be3 be"
be = re.findall('(\bbe\b)', text, re.IGNORECASE)
print(len(be))
print(be)

Result:

  

6
  ['be', 'be', 'be', 'Be', 'Be', 'be']

According to documentation , \b matches in beginning or end of words, in the example above how it is before and after be it is ensuring that what is being searched is a be that has before or after it only characters of space, period, comma, beginning end of line. >

See working on Ideone: link

    
11.08.2017 / 16:21