Machine Learning in Action学习笔记(1)----python2与python3的一些区别
阳德润
2023-12-01
下面是本人正在学习Python时遇到的一些错误,记录下来
<<Machine Learning in Action>>
1.TypeError: ‘dict_keys’ object does not support indexing
(错误地点:程序清单3-6)
此问题为Python版本问题
#在Python2中:
firstStr = myTree.keys()[0]
#在Python3中:
firstTem = list(myTree.keys())
firstStr = firstTem[0]
2.AttributeError: 'str' object has no attribute '_name_'
(错误地点:程序清单3-6)
源代码使用Python2编写,自己使用编译器为Python3
错误语句:if type(secondDict[key]._name_=="dict"):
#test to see if the nodes are dictonaires, if not they are leaf nodes
修改后:
if type(secondDict[key]) == dict:
3.TypeError: 'builtin_function_or_method' object is not subscriptable
(错误地点:程序清单4-1)
错误语句:
returnVec[vocabList.index[word]] = 1
内建函数或者方法对象不能subscriptable
错误在index[key],原因是:index后应当是()
改正:
returnVec[vocabList.index(word)] = 1
4.TypeError: 'range' object doesn't support item deletion
(错误地点:程序清单4-5)
错误语句:
for i in range(10):
randIndex = int(random.uniform(0,len(trainingSet)))
testSet.append(trainingSet[randIndex])
del(trainingSet[randIndex])
修改后:
for i in range(10):
randIndex = int(random.uniform(0,len(trainingSet)))
testSet.append(trainingSet[randIndex])
del(list(trainingSet)[randIndex])