2015-06-06 244 views
2

我有一个尺寸为236 x 97的矩阵。当我用Python打印矩阵时,它的输出不完整,.......位于矩阵的中间。在python中生成全矩阵输出

我试图将矩阵写入测试文件,但结果完全相同。 我无法发布截图,因为我的声望不够,并且如果我选择另一个标记选项,将无法正确显示。 任何人都可以解决这个问题吗?


def build(self): 
    self.keys = [k for k in self.wdict.keys() if len(self.wdict[k]) > 1] 
    self.keys.sort() 
    self.A = zeros([len(self.keys), self.dcount]) 
    for i, k in enumerate(self.keys): 
     for d in self.wdict[k]: 
      self.A[i,d] += 1 

def printA(self): 
    outprint = open('outputprint.txt','w') 
    print 'Here is the weighted matrix' 
    print self.A 
    outprint.write('%s' % self.A) 
    outprint.close() 
    print self.A.shape 

回答

1

假设你的矩阵是一个numpy的阵列可以使用matrix.tofile(<options>)写阵列到一个文件如记录here

#!/usr/bin/env python 
# coding: utf-8 

import numpy as np 

# create a matrix of random numbers and desired dimension 
a = np.random.rand(236, 97) 

# write matrix to file 
a.tofile('output.txt', sep = ' ') 
+0

它实际上是工作的,但是输出的值与我打印的输出不同在python shell中。我想念什么? –

+0

@IrfanDary:你说的'不同'是什么意思?实际上,'stdout'上的输出被缩短了。如果我解决了您的问题,请您打勾我的答案? – albert

+0

我的意思是这个值与shell中的输出不同。我从文本文件中取出一个值,然后在shell中搜索该值,但找不到相同的值。 –

1

的问题是,你是专门保存str表示与此行文件:

outprint.write('%s' % self.A)

其中明确它转换成字符串(%s)---发电您看到的删节版本。

有很多方法来写整个矩阵输出,一个简单的办法是使用numpy.savetxt,例如:

import numpy 
numpy.savetxt('outputprint.txt', self.A) 
+0

它是否与2.7版本兼容或我应该从numpy导入的东西? ,因为它在我尝试这个时会变成错误。它说“NameError:全球名'numpy'没有定义” –

+0

@IrfanDary你必须首先导入'numpy'模块---我已经添加了相关的行到我的答案。所有模块必须先导入才能使用。如果您有兴趣,请查看[关于模块的这个简单教程](http://www.tutorialspoint.com/python/python_modules.htm) – DilithiumMatrix