我有一些在 python2 中运行良好的代码。我需要把它翻译成python3。有一点我无法理解如何适应。
这是一些代码。
有错误的函数
def gauss((x, y), x0, y0, intens, sigma):
return intens*numpy.exp(-(numpy.power(x-x0, 2)+numpy.power(y-y0, 2))/(2.*sigma**2)).ravel()
调用函数
def dofwhm(psfdata):
x = numpy.arange(psfdata.shape[1])
y = numpy.arange(psfdata.shape[0])
x, y = numpy.meshgrid(x, y)
popt, pcov = opt.curve_fit(gauss, (x, y), psfdata.ravel(), p0=[psfdata.shape[1]/2, psfdata.shape[0]/2, psfdata[psfdata.shape[1]/2, psfdata.shape[0]/2], 5.0])
return 2.355*abs(popt[3])
我得到的错误是
Traceback (most recent call last):
File "catalog.py", line 8, in <module>
import cutPsf
File "/Users/igor/GALPHAT/pypygalphat/preprocessingNew/cutPsf.py", line 9
def gauss((x, y), x0, y0, intens, sigma):
^
SyntaxError: invalid syntax
有人可以帮我如何适应python3吗?
更新:嗯,@hpaulj 的答案似乎是正确的。我发现有例程可以将 Python2 代码转换为 Python3 代码。结果在目标文件 2to3 -w cutPsf.py 上运行后,我从 hpaulj 获得了建议的解决方案。不幸的是,它导致了休闲错误:
Traceback (most recent call last):
File "catalog.py", line 323, in <module>
cutPsf.run(tempDir+galaxy.psffile, outDirFits+galaxy.psffile)
File "/Users/igor/GALPHAT/pypygalphat_p3/preprocessingNew/cutPsf.py", line 63, in run
coeffwhm = dofwhm(newPsf)
File "/Users/igor/GALPHAT/pypygalphat_p3/preprocessingNew/cutPsf.py", line 20, in dofwhm
psfdata.shape[1]/2, psfdata.shape[0]/2, psfdata[psfdata.shape[1]/2, psfdata.shape[0]/2], 5.0])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
如前所述,一切都与 Python2 完美运行......