0

The following code gives me the error

"unbalanced parenthesis at position 22"

This error is triggered at line change = re.search(word[indice], contenu) . I manage to remove the parentheses in the "contenu" variable but the error persists. Do you know what this could be due to?

import re
myTxt= open('MyFile.txt')
contenu = myTxt.read()
contenu = contenu.replace("\"","\\\"")
contenu = contenu.replace("\'", "\\\'")
contenu = contenu.replace(")", "")
contenu = contenu.replace("(", "")
for indice in range(0,len(word)):
    change = re.search(word[indice], contenu)
    if change != None:
        re.sub(word[indice], aRemplacer[indice], contenu)
        
myTxt.close()

"word" and "aRemplacer" are two tables previously created on my notebook, so the error does not come from forgetting to instantiate these variables.

Thank you in advance for any answers.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • The unbalanced parentheses are in `word[indice]`, not `contenu`. Without knowing the value of `word`, then there's no way to say why you're getting that error. –  May 20 '22 at 14:23
  • 1
    You need to escape the value of `word[indice]` so that it becomes a literal search instead of being tainted by unescaped meta characters. Check out this question [Escaping regex string](https://stackoverflow.com/questions/280435/escaping-regex-string) and use `re.escape()`. It sounds like you don't even need regex and `.find()` should suffice. – MonkeyZeus May 20 '22 at 14:35
  • Now that you mention it I didn't see that my word variable was badly encoded. Thanks you ! Thank you MonkeyZeus for your advice, I'll give it a try, it might be better than what I've been trying to do. – user60005003 May 20 '22 at 14:45

0 Answers0