【问题标题】:How to "copy-paste" blocks of text from one file to another using python?如何使用python将文本块从一个文件“复制粘贴”到另一个文件?
【发布时间】:2021-04-14 20:07:26
【问题描述】:

我正在运行一些分子模拟,并且我有一个带有坐标的文件(一个 .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 可以做到,如果有人能指出我正确的方向,我将不胜感激!

【问题讨论】:

  • 您需要这样做一次还是多次?如果只有一次,复制+粘贴可以吗?
  • 是的,我必须这样做很多次。我有 1000 个构象者,我需要对其进行测试 lol @mackorone

标签: python text python-textprocessing


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2020-03-12
    • 2020-11-06
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多