-1

I'm extremely new to coding and python so bear with me.

I want to remove all text that is in parenthesis from a text file. There are multiple sets of parenthesis with varying lengths of characters inside. From another similar post on here, I found

re.sub(r'\([^()]*\)', '', "sample.txt")

which is supposed to remove characters between () but does absolutely nothing. It runs but I get no error code.

I've also tried

intext = 'C:\\Users\\S--\\PycharmProjects\\pythonProject1\\sample.txt'
outtext = 'C:\\Users\\S--\\PycharmProjects\\pythonProject1\\EDITEDsample.txt'

with open("sample.txt", 'r') as f, open(outtext, 'w') as fo:
    for line in f:
        fo.write(line.replace('\(.*?\)', '').replace('(', " ").replace(')', " "))

which successfully removes the parenthesis but nothing inbetween them.

How do I get the characters between the parenthesis out?

EDIT: I was asked for a sample of sample.txt, these are it's contents:

Example sentence (first), end of sentence. Example Line (second), end of sentence (end).

Crow44
  • 1
  • 1

1 Answers1

-1

As you can see here, the function sub does not receive a filename as parameter, but actually it receives the text on which to work.

>>> re.sub(r'\([^()]*\)', '', "123(456)789")
'123789'

As for your second attempt, notice that string.replace does not take in REGEX expressions, only literal strings.

  • I'm sorry but I'm having a hard time understanding, re.sub replaces characters in a string that I have to provide, but how can it be used to replace characters in a text file? – Crow44 Oct 02 '20 at 03:40