【发布时间】:2018-07-17 08:35:51
【问题描述】:
我是一名物理本科生,唯一的计算机编程经验是我在暑假上过的 Python 课,所以我对 Python 的一切都很陌生。我正在编写一个 python 脚本,它将从 .xyz 文件中获取一组坐标,然后将坐标系移动到以文件中的一个坐标为中心。即将一个坐标设为0,其他所有坐标在x、y、z方向平移以匹配。
我的脚本可以读取文件并将其转换为数组,但是当我尝试更改临时数组中的值时,我收到此错误:
File "E:/Computational Python Scripts/Test.py", line 29, in Carbon_Two_Origin
Temp_Array[i][1] = XYZ_File[i][1] + 0.32101
TypeError: must be str, not float
这是导致我出现问题的整个脚本:
import numpy as np
def file_name():
while True:
file_name_input = input('Type in the name of the xyz file: ')
try:
file = open(file_name_input)
lines = file.readlines()
file.close()
Geometry = []
for line in lines:
Geometry.append(line.split())
print('You have selected', file_name_input)
return Geometry
except IOError:
print('That is not a valide file name. Try again.')
#Defines the variable XYZ_File to be the input file given by user
XYZ_File = tuple(file_name())
#REMOVE THIS LATER
print(XYZ_File)
#Generates a new set of position vectors that has the target carbon, C2, at origin.
def Carbon_Two_Origin():
Temp_Array = np.array(XYZ_File)
for i in range(len(XYZ_File)):
for j in range(len(XYZ_File[i])):
Temp_Array[i][1] = XYZ_File[i][1] + 0.32101
return Temp_Array
New_Geometry = Carbon_Two_Origin()
print(New_Geometry)
【问题讨论】:
-
XYZ_File[i][1]是字符串吗?如果不是,则需要转换。 -
您应该使用
numpy.loadtxt直接加载文件,然后使用矢量化添加(例如,要移动第一列,请执行array[:, 0] += 0.32101,如果array是您加载的变量文件) -
(如果你编辑问题以包含文件的前十行,我会告诉你我的意思是)
-
这里的主要问题是
line.split()返回为字符串列表,而不是数字 -
Temp_Array[i][1] = float(XYZ_File[i][1]) + 0.32101将解决问题。您在命令line.split()中创建了一个字符串列表,python 不支持在不同类型之间应用操作(在某些语言中是允许的);因此,您必须将字符串变量转换为float才能将其添加到另一个float变量中。