如何从数组创建的字符串中获得文本输出以保持未排序?

2024-09-25 00:35:43 发布

您现在位置:Python中文网/ 问答频道 /正文

Python/Numpy问题。最后一年物理本科。。。我有一小段代码,它根据一个公式创建一个数组(本质上是一个n×n矩阵)。我将数组重塑为一列值,从中创建一个字符串,格式化它以删除多余的括号等,然后将结果输出到保存在用户文档目录中的文本文件中,然后由另一个软件使用。问题是高于“n”的某个值,输出只给出前三个值和后三个值,中间有“…”。我认为Python会自动删减最终结果以节省时间和资源,但是我需要在最终文本文件中包含所有这些值,不管处理需要多长时间,而且我一辈子都找不到如何阻止它这样做。相关代码复制到下面。。。你知道吗

import numpy as np; import os.path ; import os

'''
Create a single column matrix in text format from Gaussian Eqn.
'''

save_path = os.path.join(os.path.expandvars("%userprofile%"),"Documents")
name_of_file = 'outputfile' #<---- change this as required.
completeName = os.path.join(save_path, name_of_file+".txt") 

matsize = 32

def gaussf(x,y): #defining gaussian but can be any f(x,y)
pisig = 1/(np.sqrt(2*np.pi) * matsize) #first term
sumxy = (-(x**2 + y**2)) #sum of squares term
expden = (2 * (matsize/1.0)**2) # 2 sigma squared
expn = pisig * np.exp(sumxy/expden) # and put it all together
return expn

matrix = [[ gaussf(x,y) ]\
for x in range(-matsize/2, matsize/2)\
for y in range(-matsize/2, matsize/2)] 

zmatrix = np.reshape(matrix, (matsize*matsize, 1))column

string2 = (str(zmatrix).replace('[','').replace(']','').replace(' ', ''))

zbfile = open(completeName, "w")
zbfile.write(string2)
zbfile.close()

print completeName
num_lines = sum(1 for line in open(completeName)) 
print num_lines

任何帮助都将不胜感激!你知道吗


Tags: ofpath代码inimportforosnp
2条回答

您不需要摆弄numpy数组的字符串表示形式。一种方法是使用tofile

zmatrix.tofile('output.txt', sep='\n')

一般来说,如果只想写内容,就应该遍历数组/列表。你知道吗

zmatrix = np.reshape(matrix, (matsize*matsize, 1))


with open(completeName, "w") as zbfile: # with closes your files automatically
    for row in zmatrix:
        zbfile.writelines(map(str, row))
        zbfile.write("\n")

输出:

0.00970926751178
0.00985735189176
0.00999792646484
0.0101306077521
0.0102550302672
0.0103708481917
0.010477736974
0.010575394844
0.0106635442315
.........................

但是使用numpy我们只需要使用tofile

zmatrix = np.reshape(matrix, (matsize*matsize, 1))

# pass sep  or you will get binary output
zmatrix.tofile(completeName,sep="\n")

输出与上述格式相同。你知道吗

在矩阵上调用str将为您提供与您尝试print时得到的类似格式的输出,因此这就是您正在将格式化的截断输出写入文件的内容。你知道吗

考虑到您正在使用python2,使用xrange将比使用rane(创建列表)更有效,也不建议使用冒号分隔多个导入,您可以简单地:

import numpy as np, os.path, os

变量和函数名也应该使用下划线z_matrixzb_filecomplete_name等。。你知道吗

相关问题 更多 >