简体   繁体   English

使用Python删除文件中的括号和文本

[英]Remove parenthesis and text in a file using Python

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 所以第1行最终看起来像

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. 这是我到目前为止,它似乎只适用于代码的'Uiso'部分,因为没有括号。 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! 任何提示将不胜感激!

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. 您最近添加的代码中存在错误:您没有分配re.sub函数的结果。 Change re.sub(...) for line = re.sub(...) . 更改re.sub(...)line = re.sub(...)

import re

with open('file') as f:
    input = f.read()
    output = re.sub(r'\(\w*\)', '', input)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM