[英]How do I get a text output from a string created from an array to remain unshortened?
Python / Numpy問題。 本科一年級物理課程...我有一小段代碼,可以根據公式創建數組(本質上是n×n矩陣)。 我將數組重整形為一列值,從中創建一個字符串,對其進行格式化以除去多余的括號等,然后將結果輸出到保存在用戶Documents目錄中的文本文件,然后供另一軟件使用。 問題出在“ 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
任何幫助將不勝感激!
通常,如果您只想寫內容,則應該遍歷數組/列表。
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_matrix
, zb_file
, complete_name
等。
您不需要擺弄numpy
數組的字符串表示形式。 一種方法是使用tofile
:
zmatrix.tofile('output.txt', sep='\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.