【问题标题】:python : TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'str'python:TypeError:+的不支持的操作数类型:'numpy.ndarray'和'str'
【发布时间】:2016-05-22 07:50:55
【问题描述】:

我想使用此代码构建模型数据:

def modeldata(filename, ratingMatrix):
result={}
itemmatrix = matrixconvert(ratingMatrix)
current = 0
total = len(itemmatrix)

for item in itemmatrix:
    current+=1
    if current%100--0: print ("%d / %d" % (current,total))

    result[item] = neighbor
    #print result

with open(filename+".csv", "wb") as f:
    pickle.dump(result, f)

filename 变量是聚类过程的数据结果,包含 userid、itemid 和 rating, `那么 ratingMatrix 是一个包含键(用户)、子键(项目)和评分的字典

10 dict 1 {'255': 3.0}

。邻居包含相似性数据。

0 tuple 2 (1.0, '9790')

我想用上面的东西建立一个模型数据,我用这段代码运行函数

modeldata(filename, ratingMatrix)

但是,我得到了这个错误:

1 / 306
.
.
304 / 306
305 / 306
306 / 306
Traceback (most recent call last):

  File "<ipython-input-29-5af8931a8f1e>", line 1, in <module>
    modeldata(filename, ratingMatrix)

  File "<ipython-input-28-220883448026>", line 14, in modeldata
    with open(filename+".txt", "wb") as f:

TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'str'

你知道这段代码有什么问题吗?错误来自哪里,我怎样才能让它工作?

感谢您的帮助......

【问题讨论】:

  • 我可以看看你的文件名变量被声明为什么吗?它不喜欢open 行上的字符串连接
  • 抱歉是 csv,我已经更新了代码。但我仍然得到那个错误...... :(
  • @etsu 好吧 filename 想成为一个字符串,但看起来它是一个 numpy 数组?您以二进制模式打开文件是否有特殊原因?
  • 请尝试使用this tool 让您的问题更清楚。
  • @ScottStainton 不,它只是为了打开那个文件。好的,我将尝试将filename 读取为数组并将其更改为字符串。谢谢

标签: python string numpy model pickle


【解决方案1】:

你得到的错误是在 modeldata 函数中,更具体地说是写入文件的开始语句。该错误表明您无法使用“+”将字符串“.txt”添加到“numpy.ndarray”,这看起来像是来自变量文件名。确保您的文件名变量是您要写入的实际文件名,而不是 numpy 数组。

【讨论】:

  • 你能编辑你的问题并添加声明文件名变量的代码部分吗?
猜你喜欢
  • 1970-01-01
  • 2015-12-11
  • 2016-01-26
  • 2013-04-26
  • 2015-01-12
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多