如何使用python在提取零件后删除某个字符

2024-05-15 02:41:48 发布

您现在位置: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

Tags: txt脚本mywithopentempfilefirst
3条回答

要摆脱这条线,请尝试:

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在这里,你可以从文件数据中找到两个索引

  1. 0数的首次出现
  2. “我的费用”字符串的索引

zero_ind = file_data.find("0")

str_ind = file_data.find("My charges", zero_ind)

file_data[zero_ind:str_ind].split("\n")

然后只需使用'\n'分割文件数据,即可获得所需的所有项。你知道吗

相关问题 更多 >

    热门问题