[英]How to remove a certain character after the extraction of a part, using python
我有文本文件,看起来像这样:
.
.
.
-----------------------
first ATOMIC CHARGES
-----------------------
0 C : -0.157853
1 C : -0.156875
2 C : -0.143714
3 C : -0.140489
4 S : 0.058926
5 H : 0.128758
6 H : 0.128814
7 H : 0.142420
8 H : 0.140013
My charges : -0.0000000
------------------------
.
..
.
我使用下面的脚本来提取特定部分。
with open('FILE.txt', 'rb') as f:
textfile_temp = f.read()
print textfile_temp.split('first ATOMIC CHARGES')[1].split("My charges : -0.0000000")[0]
我的输出是:
-----------------------
0 C : -0.157853
1 C : -0.156875
2 C : -0.143714
3 C : -0.140489
4 S : 0.058926
5 H : 0.128758
6 H : 0.128814
7 H : 0.142420
8 H : 0.140013
我的目标是删除“-----------------------”字符,我的输出将是这样的:
0 C : -0.157853
1 C : -0.156875
2 C : -0.143714
3 C : -0.140489
4 S : 0.058926
5 H : 0.128758
6 H : 0.128814
7 H : 0.142420
8 H : 0.140013
要摆脱这一行,请尝试:
stringy = stringy.replace("--", "").strip() # assuming an even number of dashes
这将摆脱所有额外的破折号和换行符。
或者你可以将stringy分解为一个行列表,然后排除第一行
stringy = '\n'.join(stringy.splitlines()[1:])
或蛮力:
stringy = stringy.replace('-----------------------\n', '')
或者只是改变:
print textfile_temp.split('first ATOMIC CHARGES')[1].split("My charges : -0.0000000")[0]
至
print textfile_temp.split('first ATOMIC CHARGES')[1].split("My charges : -0.0000000")[0].replace('-----------------------\n', '')
使用三重'
with open('data.txt', 'r') as f:
textfile_temp = f.read()
print(textfile_temp.split('''first ATOMIC CHARGES
-----------------------''')[1].split('My charges : -0.0000000')[0])
@Hamza allal在这个,最简单的你可以从文件数据中找到两个索引,
0
号 zero_ind = file_data.find("0")
str_ind = file_data.find("My charges", zero_ind)
file_data[zero_ind:str_ind].split("\\n")
然后使用'\\ n'分割文件数据,您将获得所需的所有项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.