gpt4 book ai didi

python - 一元操作数类型错误 + : 'str'

转载 作者:IT老高 更新时间:2023-10-28 20:33:41 27 4
gpt4 key购买 nike

我无法弄清楚我在使用 Python 2.7 编写的代码时遇到的问题。我正在将引用转换为整数,但我不断收到类型异常bad operand type for unary +:'str'。有人可以帮忙吗?

import urllib2
import time
import datetime

stocksToPull = 'EBAY', 'AAPL'


def pullData(stock):
try:
print 'Currently pulling', stock
print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + \
stock + '/chartdata;type=quote;range=3y/csv'
saveFileLine = stock + '.txt'

try:
readExistingData = open(saveFileLine, 'r').read()
splitExisting = readExistingData.split('\n')
mostRecentLine = splitExisting[-2]
lastUnix = mostRecentLine.split(',')[0]
except Exception, e:
print str(e)
time.sleep(1)
lastUnix = 0

saveFile = open(saveFileLine, 'a')
sourceCode = urllib2.urlopen(urlToVisit).read()
splitSource = sourceCode.split('\n')

for eachLine in splitSource:
if 'values' not in eachLine:
splitLine = eachLine.split(',')
if len(splitLine) == 6:
if int(splitLine[0]) > int(lastUnix):
lineToWrite = eachLine + '\n'
saveFile.write(lineToWrite)
saveFile.close()

print 'Pulled', + stock
print 'Sleeping....'
print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
time.sleep(120)

except Exception, e:
print 'main loop', str(e)


for eachStock in stocksToPull:
pullData(eachStock)

当它到达 if int(splitLine[0]) > int(lastUnix): 时,我遇到了操作数异常 bad operand type for unary +: 'str' > 即使两个被比较的值在测试时都打印为整数。谁能给我一些反馈?谢谢!

这里是异常响应:

Currently pulling EBAY
2013-12-21 11:32:40
Pulled main loop bad operand type for unary +: 'str'
Currently pulling AAPL
2013-12-21 11:32:41
Pulled main loop bad operand type for unary +: 'str'`

最佳答案

你说 if int(splitLine[0]) > int(lastUnix): 造成了麻烦,但你实际上并没有显示任何暗示这一点的东西。我认为这条线是问题所在:

print 'Pulled', + stock

你明白为什么这条线会导致错误信息吗?你想要一个

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

>>> print 'Pulled ' + stock
Pulled AAAA

不是

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
File "<ipython-input-5-7c26bb268609>", line 1, in <module>
print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

您要求 Python 将 + 符号应用于像 +23 这样的字符串,得到一个正数 23,而她反对。

关于python - 一元操作数类型错误 + : 'str' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591385/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com