Seek word with accuracy

Asked

Viewed 42 times

2

Good staff I have a small text of 1859 words where I have stored it all in a variable string format. The question and the next 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’m looking 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 I have that accuracy.

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)

Upshot:

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

According to the documentation, the \\b match at the beginning or end of words, in the example above as it is before and after the be he is making sure that what is being sought is a be that has before or after it only characters of space, point, comma, beginning end of line.

See it working on Ideone: http://ideone.com/Xa55qs

  • 1

    regular expressions saving lives

  • Perfect follows my code in the ideone http://ideone.com/QbM3fP regular expression helped a lot.

  • 1

    https://pythex.org/? regex=%5Cbbe%5Cb&test_string=be%20besides%20being%20bee%20be%2C%20be. %20before%2C%20Be%20Be. %20forbe%20be_%20be3%20be&ignorecase=1&multiline=0&dotall=0&verbose=0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.