gpt4 book ai didi

Python:如何从文本文件中提取字符串以用作数据

转载 作者:行者123 更新时间:2023-11-28 18:51:55 32 4
gpt4 key购买 nike

这是我第一次编写 Python 脚本,开始时遇到了一些困难。假设我有一个名为 Test.txt 的 txt 文件,其中包含此信息。

                                   x          y          z      Type of atom
ATOM 1 C1 GLN D 10 26.395 3.904 4.923 C
ATOM 2 O1 GLN D 10 26.431 2.638 5.002 O
ATOM 3 O2 GLN D 10 26.085 4.471 3.796 O
ATOM 4 C2 GLN D 10 26.642 4.743 6.148 C

我想做的是最终编写一个脚本来找到这三个原子的质心。所以基本上我想总结那个 txt 文件中的所有 x 值,每个数字乘以一个给定的值,具体取决于原子的类型。

我知道我需要为每个 x 值定义位置,但我无法弄清楚如何使这些 x 值表示为数字而不是字符串中的 txt。我必须记住,我需要将这些数字乘以原子类型,因此我需要一种方法来为每种原子类型定义它们。谁能把我推向正确的方向?

最佳答案

mass_dictionary = {'C':12.0107,
'O':15.999
#Others...?
}

# If your files are this structured, you can just
# hardcode some column assumptions.
coords_idxs = [6,7,8]
type_idx = 9

# Open file, get lines, close file.
# Probably prudent to add try-except here for bad file names.
f_open = open("Test.txt",'r')
lines = f_open.readlines()
f_open.close()

# Initialize an array to hold needed intermediate data.
output_coms = []; total_mass = 0.0;

# Loop through the lines of the file.
for line in lines:

# Split the line on white space.
line_stuff = line.split()

# If the line is empty or fails to start with 'ATOM', skip it.
if (not line_stuff) or (not line_stuff[0]=='ATOM'):
pass

# Otherwise, append the mass-weighted coordinates to a list and increment total mass.
else:
output_coms.append([mass_dictionary[line_stuff[type_idx]]*float(line_stuff[i]) for i in coords_idxs])
total_mass = total_mass + mass_dictionary[line_stuff[type_idx]]

# After getting all the data, finish off the averages.
avg_x, avg_y, avg_z = tuple(map( lambda x: (1.0/total_mass)*sum(x), [[elem[i] for elem in output_coms] for i in [0,1,2]]))


# A lot of this will be better with NumPy arrays if you'll be using this often or on
# larger files. Python Pandas might be an even better option if you want to just
# store the file data and play with it in Python.

关于Python:如何从文本文件中提取字符串以用作数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11690939/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com