Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove parenthesis and text in a file using Python

Tags:

python

regex

I have a text file that contains something like this:

Cl1 Cl 0.21988(6) 0.2500 0.15016(5) 0.01587(14) Uani 1 2 d S T P . .
O1 O 1.05820(17) 0.2500 0.48327(16) 0.0206(3) Uani 1 2 d DS TU P . .
H2 H 1.1042 0.2224 0.3900 0.025 Uiso 0.5 1 calc DR U P . .
O2 O 0.78198(19) 0.2500 0.29119(17) 0.0306(4) Uani 1 2 d S TU P . .
N1 N 0.7887(2) 0.2500 0.92083(19) 0.0152(3) Uani 1 2 d DS TU P . .
H1 H 0.8568 0.2500 1.0305 0.018 Uiso 1 2 calc DR U P . .

I am trying to write a program that looks for parenthesis, and then removes the parenthesis and anything in between. So Line 1 would end up looking like

Cl1 Cl 0.21988 0.2500 0.15016 0.01587 Uani 1 2 d S T P . .

This is what I have so far, and it only seems to work for the 'Uiso' portion of the code, because there are no parentheses. It does not seem to take out the parentheses..

for line in myfile:

    if "Uani" in line:

        re.sub('\(\w*\)', '', line)
        print >> energy, line

    elif 'Uiso' in line:

        re.sub('\(\w*\)', '', line)
        print >> energy, line

print myfile.read()

Any tips would be appreciated!

like image 479
Michael R Avatar asked Mar 20 '26 19:03

Michael R


1 Answers

output = re.sub('\(\w*\)', '', input)

EDIT:

There's a mistake in the code you recently put: you are not assigning the result of the re.sub function. Change re.sub(...) for line = re.sub(...).

like image 64
Racso Avatar answered Mar 23 '26 08:03

Racso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!