微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用python将文本块从一个文件“复制粘贴”到另一个文件?

如何解决如何使用python将文本块从一个文件“复制粘贴”到另一个文件?

我正在运行一些分子模拟,我有一个带坐标的文件一个 .xyz 文件,它基本上是一个带有选项卡列的文件),我需要向它发送另一个文件,这将是我模拟的输入文件.

给你一张图片,这是我的输入文件和我的坐标的样子(底部还有更多的东西保持不变): inputfile.py

# One-electron Properties
# Methacrylic acid (MA0)
# Neutral
# 86.09 g/mol
memory 8 GB
molecule MA0 {
0 1
  C          2.87618       -0.84254        0.16797
  C          2.96148        0.13611        1.08491
  C          2.43047       -0.01082        2.47698
  C          3.62022        1.40750        0.67356
  O          3.45819        2.47668        1.24567
}
.
.
.

我在另一个文件生成了一些坐标。该文件看起来像: conformer_coords.xyz

15
conformer index = 0001,molecular weight is = 100.052429496,MMA.pdb
O          2.98687        0.35207        1.05259
C          2.40900        0.04400        0.02100
O          1.13058        0.37171       -0.29283
C          0.85476        1.77012       -0.33847
.
.
.

我想要做的是将 inputfile.py 中的坐标替换为 conformer_coords.xyz 中的坐标。我的构象器中的坐标位置数是已知的。我们暂时将其称为 N。所以,conformer_coords.xyz 有 N+2 行。

我基本上想从 conformer_coords.xyz 获取坐标并将它们放在

{
0 1

}(是的,那里需要 0 1)。

我该怎么办?蟒蛇能把它拉下来吗?无论如何我都在使用子进程,所以如果 awk 或 bash 可以做到,如果有人能指出我正确的方向,我将不胜感激!!

解决方法

import re
def insert_data(conformer_filepath,input_filepath,output_filepath):
    #grab conformer data
    with open(conformer_filepath,'r') as f:
        conformer_text = f.read()
    conformer_data = re.search('conformer[^\n]+\n(.+)',conformer_text,re.M|re.S).group(1)
    #this looks for the line that has conformer in it and takes all lines after it
    
    #grab input file before and after text
    with open(input_filepath,'r') as f:
        input_text = f.read()
    input_pre,input_post = re.search('(^.+\n0 1\n).+?(\n}.*)$',input_text,re.M|re.S).groups()
    #this looks for the "0 1" line and takes everything before that. Then it skips down to the next curly bracket which is at the start of a line and takes that and everything past it.

    #write them to the output file
    with open(output_filepath,'w') as f:
        f.write(input_pre + conformer_data + input_post)
        #this writes the three pieces collected to the output file

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。