我是一名物理本科生,他唯一的计算机编程经验是我在夏天接过的python课程,所以当涉及到python的所有内容时,我都非常环保。我正在编写一个python脚本,它将从.xyz文件的一组坐标中获取,然后将坐标系移动到文件中的一个坐标的中心。也就是说,一个坐标将为零,所有其他坐标将在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)
答案 0 :(得分:0)
就像保罗H所说的那样,问题是拆分返回str所以你有两个选择:将所有内容转换为在拆分或浮点操作之前浮动。我更喜欢拆分。
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([float(number) for number in 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)