0

So I have some file, and i need to check if certain words from my dic Count in certain lines of file.

I tried at first if Count[j+1] in file[i]: and it didn't work, because for example word a from dictionary will be triggered everywhere, and etc.

for i in range(lines_number):    
    for j in range(len(Count)):
        words_counter = 0
        if Count[j+1] in file[i]:
            words_counter += 1  

So i tried to go on with regulars, but I don't know how to put Count[j+1] under regular expression.

for i in range(lines_number):    
    for j in range(len(Count)):
        words_counter = 0
        if len(re.findall(r '\b Count[j+1] \b', file[i]) > 0:
            words_counter += 1  

Sentence example:

In one, people deliberately tamed cats in a process of artificial selection, as they were useful predators of vermin.

Words from dic example:

cat, a, the

a_chiren
  • 15
  • 2

1 Answers1

2

In cases like this you should use Literal String Interpolation. So your code would look like -

for i in range(lines_number):    
    for j in range(len(Count)):
        words_counter = 0
        if len(re.findall(rf"\b {Count[j+1]} \b", file[i]) > 0:
            words_counter += 1  

This specifically allows you to call your variables/lookups in the middle of r'' strings.

Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32