使用python读取并替换数学运算后的特定文本
我有一个以下格式的文本文件: 文件
我是什么感兴趣的是让 python 遍历 Atoms 块文件(第 34 行到 24033 行),隔离第 3 列(对应于原子类型),并执行以下操作:
- 仅隔离原子类型 2 和 4
- 从该原子列表中随机选择用户定义的百分比(例如随机选择类型 2 和 4 原子的 40%)
- 将 3 添加到这些选定的原子中(2->5、4->7)
- 使用更新的原子类型写入新文件
不幸的是,我没有在Python中读取/写入文本文件的大量知识,到目前为止,我能够想出的唯一伪解决方案如下:
import numpy as np
import random
data = np.loadtxt('5mer_SA.data',skiprows=33,max_rows=(24032-32))
atomType = data[:,2]
reactive = []
for i in range(len(atomType)):
if atomType[i] == 2 or atomType[i] == 4:
x = atomType[i]
reactive.append(x)
reactive_array = np.array(reactive)
p = 0.5 #user defined perecentage
newType = np.zeros(int(len(reactive_array)*p))
for j in range(len(newType)):
newType[j] = random.choice(reactive_array)+3
我正在努力是将修改后的atomTypes放回到文本文件的原始位置。任何建议将不胜感激。我的理想目标只是拥有一个函数,该函数将用户定义的百分比作为输入,并自动执行所有提到的操作,生成一个新的文本文件作为输出。
I have a text file in the following format:
File
What I am interested in is to have python go through the Atoms chunk of the file (lines 34 to 24033), isolate the 3rd column (which correspond to the atoms type), and perform the following operation:
- Isolate only atom type 2 and 4
- Randomly select a user-defined percentage from that list of atoms (e.g. randomly select 40% of type 2 and 4 atoms)
- Add 3 to those selected atoms (2->5, 4->7)
- Write the new file with the updated atom types
Unfortunately, I don't have a lot of knowledge of reading/writing text files in python and so far the only pseudo solution I was able to come up with is the following:
import numpy as np
import random
data = np.loadtxt('5mer_SA.data',skiprows=33,max_rows=(24032-32))
atomType = data[:,2]
reactive = []
for i in range(len(atomType)):
if atomType[i] == 2 or atomType[i] == 4:
x = atomType[i]
reactive.append(x)
reactive_array = np.array(reactive)
p = 0.5 #user defined perecentage
newType = np.zeros(int(len(reactive_array)*p))
for j in range(len(newType)):
newType[j] = random.choice(reactive_array)+3
What I am struggling is to put back modified atomTypes to the text file in the original position. Any suggestions will be greatly appreciated. My ideal goal would be just to have a function that takes as input the user-defined percentage and automatically perform all the mentioned operation generating a new text file as output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论