python出现问题:AttributeError: 'str' object has no attribute 'values'

图片说明图片说明

1个回答

。。你想写的是 data['y'].values() 吧

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python "AttributeError: 'str' object has no attribute 'decode'"错误
代码如下:rn=================================代码==========================rnimport rernf1=open('J:/wenjian/1/1.txt','r').read()#把整个文件读进来作为整个字符串rnf1.decode()#把byte类型转换成string类型rnf1=re.sub('abcdef','123456',f1)#替换所有符合的情况rnprint (f1)#此时已经替换成功rnf_w=open('J:/wenjian/1/replace_1.txt','wb')#新建一个文件,把替换后的内容写进去rnf1=f1.encode('utf-8')#从string转换成bytes类型rnf_w.write(f1)#必须要是bytes类型才能写进去rnf_w.close()rn======================代码======================================rn报错如下:rnTraceback (most recent call last):rn File "J:\wenjian\python\test.py", line 8, in rn f1.decode()#把byte类型转换成string类型rnAttributeError: 'str' object has no attribute 'decode'rn>>> rnrn系统是win7*64 python 3.3.1版本。rn望大侠帮助。真诚感谢。
python json报错:AttributeError: 'str' object has no attribute 'read'
#!/usr/bin/pythonrn#coding=gbkrnimport osrnimport json rnrnRes='["brief":"ooooo","class_extid":13,"create_time":你好,"face_id":4,"flag":6777217,"flag_ext":0,"level":0,"max_member":100,"memo":"m~F~M0m~Zm~@~B","name":"10502","option":2,"ul":["flag":4,"u":285,"flag":4,"u":35]]' rnrnqDic = json.load(Res)rnprint qDicrnfor i in qDic:rn print i["class_extid"]rn print i["flag"]rn for j in i["ul"]:rn print str(j["flag"]) + "===" + str(j["u"])rnrn执行后报错:rnTraceback (most recent call last):rn File "my.py", line 7, in rn qDic = json.load(Res)rn File "/usr/lib/python2.6/json/__init__.py", line 264, in loadrn return loads(fp.read(),rnAttributeError: 'str' object has no attribute 'read'rnrn请高手指点,万分感谢
学习doc2vec的时候报错:AttributeError: 'str' object has no attribute 'words'
菜鸟一枚,研究了两天实在是不知道怎么解决,请教各位大神!rnrn我用的是Python2.7.10,gensim版本是0.12.2,目前在学习doc2vec模型。rn我在看官方教程(http://radimrehurek.com/gensim/models/doc2vec.html)的时候,一开始就过不了了,教程说:rnrnMake sure you have a C compiler before installing gensim, to use optimized (compiled) doc2vec training (70x speedup [blog]).rnrnInitialize a model with e.g.:rnrn>>> model = Doc2Vec(documents, size=100, window=8, min_count=5, workers=4)rnPersist a model to disk with:rnrn>>> model.save(fname)rn>>> model = Doc2Vec.load(fname) # you can continue training with the loaded model!rnThe model can also be instantiated from an existing file on disk in the word2vec C format:rnrn>>> model = Doc2Vec.load_word2vec_format('/tmp/vectors.txt', binary=False) # C text formatrn>>> model = Doc2Vec.load_word2vec_format('/tmp/vectors.bin', binary=True) # C binary formatrnrnrn我的代码如下,其中negForPy.txt大概长这样:rn[code=text]rn标准间太差 房间还不如3星的 而且设施非常陈旧.建议酒店把老的标准间从新改善.rn服务态度极其差,前台接待好象没有受过培训,连基本的礼貌都不懂,竟然同时接待几个客人;大堂副理更差,跟客人辩解个没完,要总经理的电话投诉竟然都不敢给。要是没有作什么亏心事情,跟本不用这么怕。rn地理位置还不错,到哪里都比较方便,但是服务不象是豪生集团管理的,比较差。下午睡了一觉并洗了一个澡,本来想让酒店再来打扫一下,所以,打开了,请打扫的服务灯,可是到晚上回酒店,发现打扫得服务灯被关掉了,而房间还是没有打扫过。rn1。我住的是靠马路的标准间。房间内设施简陋,并且的房间玻璃窗户外还有一层幕墙玻璃,而且不能打开,导致房间不能自然通风,采光不好。2。吃了三顿早餐,品种少得可怜。3。二楼餐厅被租出去了,价格特贵。原来订餐时告之房客可以打九折(房间服务指南里也明明白白写的,等到结帐时却告之海鲜和酒水是不能打折的,而且没有发票,找来经理才好不容易在第二天拿到发票。综合来说与四星级差距太大了!rn1。我住的是靠马路的标准间。房间内设施简陋,并且的房间玻璃窗户外还有一层幕墙玻璃,而且不能打开,导致房间不能自然通风,采光不好。2。吃了三顿早餐,品种少得可怜。3。二楼餐厅被租出去了,价格特贵。原来订餐时告之房客可以打九折(房间服务指南里也明明白白写的,等到结帐时却告之海鲜和酒水是不能打折的,而且没有发票,找来经理才好不容易在第二天拿到发票。综合来说与四星级差距太大了!rn[/code]rnrn[code=python]rn#encoding: utf-8rnfrom gensim.models.doc2vec import Doc2Vecrnrnwith open('negForPy.txt','r') as infile:rn documents = infile.readlines()rnmodel =Doc2Vec(documents,size=100,window=8,min_count=5,workers=4)rnrnmodel = Doc2Vec.load_word2vec_format('vectors1.txt', binary = False)[/code]rnrn第8行和之前的代码是不同的两种方法,我分开运行不管哪种方法都会报错,比如就像上面那样的代码直接运行,报错是:rnTraceback (most recent call last):rn File "E:\zzWorkFiles\ZZworkspace\Practise1\src\Prac1\draft2.py", line 6, in rn model =Doc2Vec(["aaaa","andajfiaihe","dfghiah","adoifjeng"],size=100,window=8,min_count=5,workers=4)rn File "D:\programFiles\Python2.7.10\lib\site-packages\gensim-0.12.2-py2.7-win32.egg\gensim\models\doc2vec.py", line 584, in __init__rn self.build_vocab(documents, trim_rule=trim_rule)rn File "D:\programFiles\Python2.7.10\lib\site-packages\gensim-0.12.2-py2.7-win32.egg\gensim\models\word2vec.py", line 495, in build_vocabrn self.scan_vocab(sentences, trim_rule=trim_rule) # initial surveyrn File "D:\programFiles\Python2.7.10\lib\site-packages\gensim-0.12.2-py2.7-win32.egg\gensim\models\doc2vec.py", line 627, in scan_vocabrn document_length = len(document.words)rnAttributeError: 'str' object has no attribute 'words'rnrnrn这种情况下应该怎么解决处理呢??rn跪求大神解答!rn
AttributeError: 'str' object has no attribute 'get' 请高手赐教
class TestBaidu(unittest.TestCase):rn URL = Config().getElement('URL');rnrn上述getElement()方法是调用另一个类中的方法rnrnclass Config: rn def getElement(self,element,index=0):rn return self.configuration[index].get(element);rnrnrnrn运行报错:rnTraceback (most recent call last):rn File "D:\自动化测试\workspace\AutoTestPro\testCase\test_baidu.py", line 12, in rn class TestBaidu(unittest.TestCase):rn File "D:\自动化测试\workspace\AutoTestPro\testCase\test_baidu.py", line 14, in TestBaidurn URL = Config().getElement('URL');rn File "D:\自动化测试\workspace\AutoTestPro\utils\configuration.py", line 22, in getElementrn return self.configuration[index].get(element);rnAttributeError: 'str' object has no attribute 'get'rnrnrn请高手赐教,为什么会报错,怎么解决呢?万分感谢!!!
AttributeError: 'Settings' object has no attribute 'DATABASE_ENGINE'
环境:Centos、python2.7.7 Django:1.7 south:0.7rnsettings.py 里的部分配置:rnINSTALLED_APPS = (rn 'south',rn 'django.contrib.admin',rn 'django.contrib.auth',rn 'django.contrib.contenttypes',rn 'django.contrib.sessions',rn 'django.contrib.messages',rn 'django.contrib.staticfiles',rn 'polls'rn)rn其中south:为同步模型到数据库的第三方模块,用来取代syncdb。rnpolls:为自己的投票应用。rn目前我执行python manage.py syncdb或者python manage.py startmigration polls --initial均报错,报错信息如下:rnTraceback (most recent call last):rn File "manage.py", line 10, in rn execute_from_command_line(sys.argv)rn File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 385, in execute_from_command_linern utility.execute()rn File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 377, in executern self.fetch_command(subcommand).run_from_argv(self.argv)rn File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 238, in fetch_commandrn klass = load_command_class(app_name, subcommand)rn File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 41, in load_command_classrn module = import_module('%s.management.commands.%s' % (app_name, name))rn File "/usr/local/python2.7/lib/python2.7/importlib/__init__.py", line 37, in import_modulern __import__(name)rn File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.6-py2.7.egg/south/management/commands/syncdb.py", line 5, in rn from south import migrationrn File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.6-py2.7.egg/south/migration.py", line 17, in rn from south.db import dbrn File "/usr/local/python2.7/lib/python2.7/site-packages/South-0.6-py2.7.egg/south/db/__init__.py", line 9, in rn module_name = '.'.join(['south.db', settings.DATABASE_ENGINE])rn File "/usr/local/python2.7/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/conf/__init__.py", line 47, in __getattr__rn return getattr(self._wrapped, name)rn[color=#FF0000]AttributeError: 'Settings' object has no attribute 'DATABASE_ENGINE'[/color]
AttributeError: 'dict' object has no attribute 'status_code'
刚学python和django框架。出现的错误AttributeError: 'dict' object has no attribute 'status_code'这个错误是什么导致的?怎么解决?求大神指导!!!
AttributeError: '_NamespacePath' object has no attribute 'sort'
python3.6安装six包报错,报错信息为:AttributeError: '_NamespacePath' object has no attribute 'sort'rn执行pip list命令也报同样的错。rn环境为64位windows 10,已安装anaconda3rn求大神指导,谢谢![img=https://img-bbs.csdn.net/upload/201705/16/1494935625_44723.png][/img]
AttributeError: 'module' object has no attribute 'rcParams'
电脑系统win7 x64rn电脑同时安装了python2.7和python3.4rn也同时安装了matplotlib for 2.7 和3.4rnrn在pycharm py文件中import matplotlib正常(解释器为python 3.4)rnprint(matplotlib.__file__ )rnD:\python3.4.2\lib\site-packages\matplotlib\__init__.pyrnrn但在python console中import matplotlib出现错误:(解释器也为python 3.4)rnAttributeError: 'module' object has no attribute 'rcParams'rnrn网上在解决说:(应该是针对linux)rnit looks like you have a matplotlib dir in your working directory that is being picked up and you probably don't want it. rnrnYou have the matplotlib source directory in your HOME directory and when you run from your home directory, it is being picked up instead of the installation directory. I usually name my src tree "mpl" to avoid this problem rn这个好像不行
AttributeError: 'module' object has no attribute 'dumps'
[code=python]rnimport jsonrnd = dict(name='Bob', age=20, score=88)rnjson.dumps(d)rn[/code]rnrn以上代码在命令行输入运行结果是正确的,但是在pycharm中总是报如下错误:rn[code=text]rnTraceback (most recent call last):rn File "/home/zong/PycharmProjects/first/json.py", line 1, in rn import jsonrn File "/home/zong/PycharmProjects/first/json.py", line 3, in rn json.dumps(d)rnAttributeError: 'module' object has no attribute 'dumps'rn[/code]rnrn什么原因?怎么解决?
AttributeError: 'module' object has no attribute 'LWPCookieJar'
[code=python]import cookielibrnrndef test():rn ck = cookielib.LWPCookieJar()rnrntest()[/code]rnrnrn为什么提示如下错误:rnAttributeError: 'module' object has no attribute 'LWPCookieJar'
'str' object has no attribute 'get'咋解决?
本人学医,凭兴趣自学python,真心不易,现在遇到一个问题:在写一个简单的注册提交页面,是想通过class将数据存储到本地的txt文件,在输入username和password,submit到register/add时,但遇到了下面的问题:rnrn![图片说明](https://img-ask.csdn.net/upload/201801/27/1517032413_303388.jpg)rnrn请各位大神帮助看是什么问题。rnrn下面是源代码,看看还有没有其他什么问题。谢谢!rnrnrn app.pyrn rn```rn from flask import (rn Flask,rn render_template,rn request,rn redirect,rn)rnrnfrom Models import (Users, Requirements)rnimport timernimport osrnrnapp = Flask(__name__)rnrn@app.route('/', methods=['GET'])rndef index():rn return render_template('/index.html')rnrnrn@app.route('/login')rndef login():rn return render_template('/login.html')rnrnrn@app.route('/register')rndef register():rn return render_template('/register.html')rnrnrn@app.route('/register/add', methods=['POST'])rndef register_add():rnrn if request.method == 'POST':rn form = request.formrn print('打印', form)rn u = Users.new(form)rn u.save()rnrn return redirect('/login')rnrnrn@app.route('/post', methods=['GET'])rndef post_message():rn return render_template('/post.html')rnrnrn@app.route('/post/add', methods=['POST'])rndef post_add():rnrn if request.method == 'POST':rn form = request.formrn u = Requirements(form)rn u = Requirements.new(form)rn u.save()rnrn return redirect('/post')rnrnrnif __name__ == '__main__':rn config = dict(rn debug=True,rn host='0.0.0.0',rn port=2000,rn )rn app.run(**config)rnrn```rnrnrnModel.pyrnrn```rn from random import Randomrnimport jsonrnimport osrnrnrndef save(data, path):rnrn m = json.dumps(data, ensure_ascii=False)rn # path = os.path.dirname(__file__)rn with open(path, 'a+') as f:rn f.read()rn f.write(m + '\n')rn f.close()rnrnrndef load(path):rn with open(path, 'r', encoding='utf-8') as f:rn s = f.read()rn m = json.dumps(s, ensure_ascii=False)rn print('加载', type(m), m)rn t = json.loads(m)rn print('加载', type(t), t)rn return trnrnrndef random_str(randomlength=16):rn s = ''rn chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'rn length = len(chars) - 1rn random = Random()rn for i in range(randomlength):rn s += chars[random.randint(0, length)]rn return srnrnrnclass Model(object):rnrn @classmethodrn def db_path(cls):rn root = os.path.dirname(__file__)rn classname = cls.__name__rn path = '/data/.txt'.format(root, classname)rn return pathrnrnrn @classmethodrn def all(cls):rn """rn all 方法(类里面的函数叫方法)使用 load 函数得到所有的 modelsrn """rn path = cls.db_path()rn models = load(path)rn ms = [cls.new(m) for m in models]rn return msrnrn @classmethodrn def new(cls, form):rn m = cls(form)rn return mrnrnrn def save(self):rn models = self.all()rn path = self.db_path()rn l = [m.__dict__ for m in models]rn save(l, path)rnrnrnclass Users(Model):rn def __init__(self, form):rn self.id = random_str()rn self.username = form.get('username', '')rn self.password = form.get('password', '')rnrnrnclass Requirements(Model):rn def __init__(self, form):rn self.id = form.get('id', None)rn self.province = form.get('province', '')rn self.city = form.get('city', '')rn self.post_content = form.get('post_content', '')rn self.contact_requirement_method = form.get('contact_requirement_method', '')rnrn```rnrnrn最后搞定了,采取了下面这种方式,然后有修改了Model部分内容rnrnrn```rn if request.method == 'POST':rn formdata = request.formrn form = formdata.to_dict()rn u = Users.new(form)rn u.save()rnrn```rnrnrn
Python 3.7 AttributeError: 'str' object has no attribute 'items' 报错怎么解决
![图片说明](https://img-ask.csdn.net/upload/201901/23/1548240235_359645.png)rn求大佬帮忙看下这样的报错怎么解决
python英文去停用词,报错 'str' object has no attribute
各位大神,请问这个错误啥子意思呀?n'str' object has no attribute 'word'n![图片说明](https://img-ask.csdn.net/upload/201702/11/1486818276_296519.jpg)
Scrapy无法正常运行AttributeError: 'module' object has no attribute 'F_GETFD'
在win7环境上装scrapy,相关的依赖包比如lxml之类的都装好了,可以成功的运行import scrapy命令。当在CMD里运行scrapy shell www.baidu.com时就会报错,请问这个问题如何修复?rn[img=https://img-bbs.csdn.net/upload/201705/29/1496048097_8107.png][/img]rn[img=https://img-bbs.csdn.net/upload/201705/29/1496048111_970088.png][/img][img=https://img-bbs.csdn.net/upload/201705/29/1496048124_400617.png][/img][img=https://img-bbs.csdn.net/upload/201705/29/1496048135_502665.png][/img]rnrn同样的操作在别的几台机器上都没问题了,就在一台电脑上出了这个问题,求教,,,,,,,,,
报错AttributeError: 'QWidget' object has no attribute 'setCentralWidget'如何解决
# -*- coding: utf-8 -*-rnrn# Form implementation generated from reading ui file 'sign.ui'rn#rn# Created: Sun Nov 13 17:09:05 2016rn# by: PyQt4 UI code generator 4.11.3rn#rn# WARNING! All changes made in this file will be lost!rnrnimport sysrnfrom PyQt4 import QtCore, QtGuirnrntry:rn _fromUtf8 = QtCore.QString.fromUtf8rnexcept AttributeError:rn def _fromUtf8(s):rn return srnrntry:rn _encoding = QtGui.QApplication.UnicodeUTF8rn def _translate(context, text, disambig):rn return QtGui.QApplication.translate(context, text, disambig, _encoding)rnexcept AttributeError:rn def _translate(context, text, disambig):rn return QtGui.QApplication.translate(context, text, disambig)rnrnclass Ui_MainWindow(object):rn def setupUi(self, MainWindow):rn MainWindow.setObjectName(_fromUtf8("MainWindow"))rn MainWindow.resize(747, 564)rn self.centralwidget = QtGui.QWidget(MainWindow)rn self.centralwidget.setObjectName(_fromUtf8("centralwidget"))rn self.label = QtGui.QLabel(self.centralwidget)rn self.label.setGeometry(QtCore.QRect(50, 30, 211, 61))rn self.label.setStyleSheet(_fromUtf8("\n"rn"font: 75 22pt \"Microsoft YaHei UI\";"))rn self.label.setObjectName(_fromUtf8("label"))rn self.label_2 = QtGui.QLabel(self.centralwidget)rn self.label_2.setGeometry(QtCore.QRect(50, 120, 81, 18))rn self.label_2.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";"))rn self.label_2.setObjectName(_fromUtf8("label_2"))rn self.lineEdit = QtGui.QLineEdit(self.centralwidget)rn self.lineEdit.setGeometry(QtCore.QRect(50, 150, 331, 25))rn self.lineEdit.setObjectName(_fromUtf8("lineEdit"))rn self.label_3 = QtGui.QLabel(self.centralwidget)rn self.label_3.setGeometry(QtCore.QRect(50, 200, 81, 18))rn self.label_3.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";"))rn self.label_3.setObjectName(_fromUtf8("label_3"))rn self.lineEdit_2 = QtGui.QLineEdit(self.centralwidget)rn self.lineEdit_2.setGeometry(QtCore.QRect(50, 230, 331, 25))rn self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))rn self.label_4 = QtGui.QLabel(self.centralwidget)rn self.label_4.setGeometry(QtCore.QRect(50, 280, 81, 18))rn self.label_4.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";"))rn self.label_4.setObjectName(_fromUtf8("label_4"))rn self.lineEdit_3 = QtGui.QLineEdit(self.centralwidget)rn self.lineEdit_3.setGeometry(QtCore.QRect(50, 310, 331, 25))rn self.lineEdit_3.setObjectName(_fromUtf8("lineEdit_3"))rn self.pushButton = QtGui.QPushButton(self.centralwidget)rn self.pushButton.setGeometry(QtCore.QRect(50, 380, 112, 34))rn self.pushButton.setStyleSheet(_fromUtf8("font: 9pt \"Microsoft YaHei UI\";\n"rn"background-color: rgb(215, 215, 215);"))rn self.pushButton.setObjectName(_fromUtf8("pushButton"))rn MainWindow.setCentralWidget(self.centralwidget)rn self.menubar = QtGui.QMenuBar(MainWindow)rn self.menubar.setGeometry(QtCore.QRect(0, 0, 747, 30))rn self.menubar.setObjectName(_fromUtf8("menubar"))rn MainWindow.setMenuBar(self.menubar)rn self.statusbar = QtGui.QStatusBar(MainWindow)rn self.statusbar.setObjectName(_fromUtf8("statusbar"))rn MainWindow.setStatusBar(self.statusbar)rnrn self.retranslateUi(MainWindow)rn QtCore.QMetaObject.connectSlotsByName(MainWindow)rnrn def retranslateUi(self, MainWindow):rn MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))rn self.label.setText(_translate("MainWindow", "欢迎注册", None))rn self.label_2.setText(_translate("MainWindow", "名字", None))rn self.label_3.setText(_translate("MainWindow", "密码", None))rn self.label_4.setText(_translate("MainWindow", "重复密码", None))rn self.pushButton.setText(_translate("MainWindow", "注册", None))rnrnif __name__ == "__main__":rn app = QtGui.QApplication(sys.argv)rn Form = QtGui.QWidget()rn ui = Ui_MainWindow()rn ui.setupUi(Form)rn Form.show()rn sys.exit(app.exec_())rnrnPython菜鸟,想简单实现一个用户注册注册界面,还没有与数据库进行连接,运行时报错rnTraceback (most recent call last):rn File "D:/PyCharm 2016.2.3/example/Sign.py", line 88, in rn ui.setupUi(Form)rn File "D:/PyCharm 2016.2.3/example/Sign.py", line 64, in setupUirn MainWindow.setCentralWidget(self.centralwidget)rnAttributeError: 'QWidget' object has no attribute 'setCentralWidget'rnrn求大神告知解决办法。rnrnrn
请求急救 AttributeError: 'module' object has no attribute 'pack'
[code=python]rn#!/usr/bin/env pythonrn# -*- coding: utf-8 -*-rn# @Date :rn# @Author :rn# @Link :rn# @Version :rnrnimport webrnrnurls=('/test','Test')rnrnapp = web.application(urls,globals())rnrnclass Test:rn def GET(self):rn return 'GetTest'rn rn def PUT(self):rn return 'PutTest'rnrn def POST(self):rn return 'PostTest'rnrn def DELETE(self):rn return 'DeleteTest'rnrnif __name__ == '__main__':rn app.run()rnrn[/code]rnrn以上是我的Python代码,文件名是rest.pyrnrn下面是问题所在:rnroot@ubuntu:/home/webService# python rest.pyrnTraceback (most recent call last):rn File "rest.py", line 8, in rn import webrn File "/usr/local/python2.7/lib/python2.7/site-packages/web/__init__.py", line 14, in rn import utils, db, net, wsgi, http, webapi, httpserver, debugerrorrn File "/usr/local/python2.7/lib/python2.7/site-packages/web/utils.py", line 36, in rn import subprocessrn File "/usr/local/python2.7/lib/python2.7/subprocess.py", line 430, in rn import picklern File "/usr/local/python2.7/lib/python2.7/pickle.py", line 171, in rn class Pickler:rn File "/usr/local/python2.7/lib/python2.7/pickle.py", line 250, in Picklerrn def put(self, i, pack=struct.pack):rnAttributeError: 'module' object has no attribute 'pack'rnrn怎么办啊,各位大神?昨天运行的好好的,代码什么也没动,环境什么也没改,今天就成这个样了。Python也重装过了,但还是这个样子~~~
python代码报错(AttributeError: 'NoneType' object has no attribute 'run_line_magic')
import pandas as pdrnimport matplotlib.pyplot as plt,matplotlib.image as mpimgrnfrom sklearn.model_selection import train_test_splitrnfrom sklearn import svmrn[b]#~matplotlib inlinernfrom IPython import get_ipythonrnget_ipython().run_line_magic('matplotlib','iinline')[/b][color=#FF0000][/color]rnrnimport matlpotlibrnrnlabeled_images = pd.read_csv('D:/kaggle/train.csv')rnimages = labeled_images.iloc[0:5000,1:]rnlabels = labeled_images.iloc[0:5000,:1]rntrain_images,test_images,train_labels,test_labels = train_test_split(rn images,labels,train_size=0.8)rn rni=1rnimg = train_images.iloc[i].as_matrix()rnimg = img.reshape((28,28))rnplt.imshow(img,cmap='gray')rnplt.title(train_labels.iloc[i,0])rn主要是我想画图,如下[img=https://img-bbs.csdn.net/upload/201712/06/1512547153_833788.png][/img]rn[b]%matlpotlib inline会报错 invalid syntax,上网搜了下用ipython里的run_line_magic也不行[/b]所以想来问下大家rnrn小白的软件配置是:python3.6 和Geany
执行python代码报错(AttributeError: 'NoneType' object has no attribute 'magic')
执行python代码报错,在网上查了很久,都没有查到解决办法,请大神指导一下!谢谢!rnrn[root@master dataannl]# python -VrnPython 3.6.2rn[root@master dataannl]# rn[root@master dataannl]# rn[root@master dataannl]# cat example01.pyrn# -*- coding: utf-8 -*-rnrn# from pandas import Series,DataFramern# import pandas as pdrnrnfrom IPython import get_ipythonrnimport matplotlib.pyplot as pltrnget_ipython().magic(u'matplotlib inline')rnrnplt.ylabel('True Positive Rate') #坐标轴标签rnplt.ylim(0,1.05) #边界范围rnplt.xlim(0,1.05) #边界范围rnplt.legend(loc=4) #图例rnplt.show() #显示作图结果rnrn[root@master dataannl]# rn[root@master dataannl]# python example01.pyrnTraceback (most recent call last):rn File "example01.py", line 8, in rn get_ipython().magic(u'matplotlib inline')rnAttributeError: 'NoneType' object has no attribute 'magic'rn[root@master dataannl]#
AttributeError: 'WebDriverWait' object has no attribute 'click',求帮忙查看原因
[img=https://img-bbs.csdn.net/upload/201804/17/1523930015_520806.png][/img] rnrnrn请问有大神知道是什么原因吗?
求助 关于Django ,AttributeError:'Topic' object has no attribute 'owner'
python编程入门到实践第十九章中的问题rnrnrn浏览器报错信息如下rnrn![图片说明](https://img-ask.csdn.net/upload/201904/04/1554356911_216497.png)rnrnrn**关于我的views.py 的代码如下**rnrn```rnfrom django.shortcuts import renderrnfrom django.http import HttpResponseRedirect, Http404rnfrom django.urls import reversernfrom django.contrib.auth.decorators import login_requiredrnrnfrom .models import Topic, Entryrnfrom .forms import TopicForm, EntryFormrnrnrnrn# Create your views here.rndef index(request):rn '''rn 学习笔记的主页rn :return:rn '''rn return render(request,'learning_logs/index.html')rndef topics(request):rn """Show all topics."""rn topics = Topic.objects.order_by('date_added')rn context = 'topics': topicsrn return render(request, 'learning_logs/topics.html', context)rnrnrnrnrn@login_requiredrndef new_topic(request):rn '''添加新主题'''rn if request.method != 'POST':rn form = TopicForm()rn else:rn form = TopicForm(request.POST)rn if form.is_valid():rn form.save()rn return HttpResponseRedirect(reverse('learning_logs:topics'))rn context = 'form':formrn return render(request,'learning_logs/new_topic.html',context)rnrnrndef edit_entry(request, entry_id):rn """Edit an existing entry."""rn entry = Entry.objects.get(id=entry_id)rn topic = entry.topicrn if topic.owner != request.user:rn raise Http404rnrn if request.method != 'POST':rn # Initial request; pre-fill form with the current entry.rn form = EntryForm(instance=entry)rn else:rn # POST data submitted; process data.rn form = EntryForm(instance=entry, data=request.POST)rn if form.is_valid():rn form.save()rn return HttpResponseRedirect(reverse('learning_logs:topic',rn args=[topic.id]))rnrn context = 'entry': entry, 'topic': topic, 'form': formrn return render(request, 'learning_logs/edit_entry.html', context)rnrnrndef topic(request, topic_id):rn """Show a single topic, and all its entries."""rn topic = Topic.objects.get(id = topic_id)rn # Make sure the topic belongs to the current user.rn if topic.owner != request.user:rn raise Http404rnrn entries = topic.entry_set.order_by('-date_added')rn context = 'topic': topic, 'entries': entriesrn return render(request, 'learning_logs/topic.html', context)rnrnrndef new_entry(request, topic_id):rn """Add a new entry for a particular topic."""rn topic = Topic.objects.get(id=topic_id)rn if topic.owner != request.user:rn raise Http404rnrn if request.method != 'POST':rn # No data submitted; create a blank form.rn form = EntryForm()rn else:rn # POST data submitted; process data.rn form = EntryForm(data=request.POST)rn if form.is_valid():rn new_entry = form.save(commit=False)rn new_entry.topic = topicrn new_entry.save()rn return HttpResponseRedirect(reverse('learning_logs:topic',rn args=[topic_id]))rnrn context = 'topic': topic, 'form': formrn return render(request, 'learning_logs/new_entry.html', context)rnrnrnrnrn```
错误:“AttributeError: module 'aiml' has no attribute 'Kernel'
初学Python 3.X,按照网页上的关于aiml的例子写了如下代码,运行总是报错:rnC:\Users\lenovo\PycharmProjects\aimltest\venv\Scripts\python.exe C:/Users/lenovo/PycharmProjects/aimltest/test1.pyrnTraceback (most recent call last):rn File "C:/Users/lenovo/PycharmProjects/aimltest/test1.py", line 17, in rn alice=aiml.Kernel()rnAttributeError: module 'aiml' has no attribute 'Kernel'rnC:\Users\lenovo\PycharmProjects\aimltest\venv\lib\site-packages\aiml\alicernrnProcess finished with exit code 1rn检查了目录,aiml下面也有Kernel.py,请问如何解决,谢谢大侠!rn-----------------------源代码------------------------------------rnrn# -*- coding: utf-8 -*-rnimport aimlrnimport sysrnimport osrnrndef get_module_dir (name):rnrn path = getattr(sys.modules[name], '__file__', None)rn if not path:rn raise AttributeError('模块 %s 没有 属性 __file__'%name)rn return os.path.dirname(os.path.abspath(path))rnrnalice_path =get_module_dir('aiml') +'\\alice'rnrnos.chdir(alice_path)rnprint(alice_path)rnalice=aiml.Kernel()rnalice.learn("std-startup.xml")rnalice.respond("load aiml b")rnrnwhile True:rn print(alice.respond(input("Enter your message >>")))rnrn
AttributeError: module 'request' has no attribute 'args'
我在看flask教学视频rn模仿里面的代码rn@app.route('/login/')rndef login():rn print(request.args)rn print(request.args.get('q1'))rn return render_template('login.html')rnrnlogin.html里rnrnrnrn rn 登陆页面rnrnrn 点我搜索rnrnrnrn代码和视频基本一样,结果运行显示此帖标题字样,我的是py3.x,不知道是不是这个原因,没有args这个方法
AttributeError: '_NamespacePath' oject has no attribute 'sort'
win10 环境。安装anaconda,python3.6。能运行python程序,但是输入pip list,或者其他pip命令,jupyter notebook。都会报这个错误。rn错误的详细截图:rn[img=https://img-bbs.csdn.net/upload/201704/01/1491056337_884908.png][/img]rn请问大神怎么解决?
AttributeError: module 'jieba' has no attribute 'cut' python3.6
AttributeError: module 'jieba' has no attribute 'cut'rnrnpython3.6rnrn这个问题怎么解决。
list object has no attribute location python
我刚使用python写程序,然后总是报错list object has no attribute location,为什么?我应该怎么处理呢?n
Python 运行报错: 'WebDriver' object has no attribute 'find_element_by_Xpath'
[img=https://img-bbs.csdn.net/upload/201812/25/1545720592_267528.png][/img]
求助,python的'dict' object has no attribute 'key'
class Fridge:rnrnrndef __init__(self,items=):rnif type(items)!=type():rnraise TypeError("Fridge requires a dictionary but was given %s" %type(items))rnself.items=itemsrnreturnrnrnrndef __add_multi(self,food_name,quantity):rnif (not food_name in self.items):rnself.items[food_name] = 0rnself.items[food_name]=self.items[food_name] + quantityrnrnrndef add_one(self,food_name):rnif type(food_name)!=type(''):rnraise TypeError("add_one requires a string, given a %s"%type(food_name))rnelse:rnself.__add_multi(food_name,1)rnreturn Truernrnrndef add_many(self,food_dict):rnif type(food_dict)!=type():rnraise TypeError("add_many requires a dictionary, got a %s" %type(food_dict))rnfor item in food_dict.key():rnself.__add_multi(item,food_dict[item])rnreturnrn错误:rnTraceback (most recent call last):rnFile "", line 1, in rnFile "Fridge.py", line 26, in add_manyrnfor item in food_dict.key():rnAttributeError: 'dict' object has no attribute 'key'
python报错:AttributeError: module 'curses' has no attribute 'wrapper'
windows平台 rnpython3.7.0rn在vscode下运行程序时rn其中curses.wrapper(main)报错rnrnrn```rnPS E:\dai ma\aaa> C:/Users/夏洛洛/AppData/Local/Programs/Python/Python37/python.exe "e:/dai ma/aaa/项目/2048.py"rnTraceback (most recent call last):rn File "e:/dai ma/aaa/项目/2048.py", line 219, in rn curses.wrapper(main)rnAttributeError: module 'curses' has no attribute 'wrapper'rnrn```rnrn 查询了下这个错误,可能是文件名并没有发生冲突,但换文件名后并没有排除。难道是windows平台问题吗?rn 求解,感激不尽。
python运行出错AttributeError: neuralnetwork instance has no attribute 'predict'
有两个py文件。rn一个是NeuralNetwork.py,代码如下:rnimport numpy as nprnrnrndef tanh(x):rn return np.tanh(x)rnrnrndef tanh_deriv(x):rn return 1.0 - np.tanh(x) * np.tanh(x)rnrnrndef logistic(x):rn return 1 / (1 + np.exp(-x))rnrnrndef logistic_derivative(x):rn return logistic(x) * (1 - logistic(x))rnrnrnclass neuralnetwork:rn def __init__(self, layers, activation='tanh'):rnrn if activation == 'logistic':rn self.activation = logisticrn self.activation_deriv = logistic_derivativern elif activation == 'tanh':rn self.activation = tanhrn self.activation_deriv = tanh_derivrnrn self.weights = []rn for i in range(1, len(layers) - 1):rn self.weights.append((2 * np.random.random((layers[i - 1] + 1, layers[i] + 1)) - 1) * 0.25)rn self.weights.append((2 * np.random.random((layers[i] + 1, layers[i + 1])) - 1) * 0.25)rnrn def fit(self, X, y, learning_rate=0.2, epochs=10000):rn X = np.atleast_2d(X)rn temp = np.ones([X.shape[0], X.shape[1] + 1])rn temp[:, 0:-1] = Xrn X = temprn y = np.array(y)rnrn for k in range(epochs):rn i = np.random.randint(X.shape[0])rn a = [X[i]]rnrn for l in range(len(self.weights)):rn a.append(self.activation(np.dot(a[l], self.weights[l])))rn error = y[i] - a[-1]rn deltas = [error * self.activation_deriv(a[-1])]rnrn for l in range(len(a) - 2, 0, -1):rn deltas.append(deltas[-1].dot(self.weights[l].T) * self.activation_deriv(a[l]))rn deltas.reverse()rn for i in range(len(self.weights)):rn layer = np.atleast_2d(a[i])rn delta = np.atleast_2d(deltas[i])rn self.weights[i] += learning_rate * layer.T.dot(delta)rnrn def predict(self, x):rn x = np.array(x)rn temp = np.ones(x.shape[0] + 1)rn temp[0:-1] = xrn a = temprn for l in range(0, len(self.weights)):rn a = self.activation(np.dot(a, self.weights[l]))rn return arnrn另一个是SimpleTest.py,代码如下:rnfrom NeuralNetwork import neuralnetworkrnimport numpy as nprnrnnn = neuralnetwork([2,2,1], 'tanh')rnX = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])rny = np.array([0, 1, 1, 0])rnnn.fit(X, y)rnfor i in [[0, 0], [0, 1], [1, 0], [1, 1]]:rn print (i, nn.predict(i))rnrn运行SimpleTest.py时出错,提示如下:rnD:\Users\dell\Anaconda2\python.exe D:/PyCharm/neuralNetwork/SimpleTest.pyrnTraceback (most recent call last):rn File "D:/PyCharm/neuralNetwork/SimpleTest.py", line 9, in rn print (i, nn.predict(i))rnAttributeError: neuralnetwork instance has no attribute 'predict'rnrnProcess finished with exit code 1
Python中PyMySQL提示AttributeError: module 'socket' has no attribute 'AF_UNIX'
代码如下:rnfrom urllib.request import urlopenrnfrom bs4 import BeautifulSouprnimport rernimport datetimernimport randomrnimport pymysqlrnrnconn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock',rn user='root', passwd=None, db='mysql', charset='utf8')rncur = conn.cursor()rncur.execute("USE scraping")rnrnrandom.seed(datetime.datetime.now())rnrndef store(title, content):rn cur.execute("INSERT INTO pages (title, content) VALUES (\"%s\",\rn \"%s\")", (title, content))rn cur.connection.commit()rn rndef getLinks(articleUrl):rn html = urlopen("http://en.wikipedia.org"+articleUrl)rn bsObj = BeautifulSoup(html)rn title = bsObj.find("h1").get_text()rn content = bsObj.find("div", "id":"mw-content-text").find("p").get_text()rn store(title, content)rn return bsObj.find("div", "id":"bodyContent").findAll("a",rn href=re.compile("^(/wiki/)((?!:).)*$"))rnlinks = getLinks("/wiki/Kevin_Bacon")rntry:rn while len(links) > 0:rn newArticle = links[random.randint(0, len(links)-1)].attrs["href"]rn print(newArticle)rn links = getLinks(newArticle)rnfinally:rn cur.close()rn conn.close()rnrn编译后提示错误:rnTraceback (most recent call last):rn File "F:\爬虫\17-9-11.py", line 9, in rn user='root', passwd=None, db='mysql', charset='utf8')rn File "F:\Python 3.6\lib\site-packages\pymysql\__init__.py", line 90, in Connectrn return Connection(*args, **kwargs)rn File "F:\Python 3.6\lib\site-packages\pymysql\connections.py", line 706, in __init__rn self.connect()rn File "F:\Python 3.6\lib\site-packages\pymysql\connections.py", line 903, in connectrn sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)rn[color=#FF0000]AttributeError: module 'socket' has no attribute 'AF_UNIX'[/color]
'int' object has no attribute '__getitem__'
小白最近正在学Python 数据挖掘入门与实践一书,在书的1.3章节亲和性分析中遇到一个问题,久久不能解决:rn原书第9页第11行: if sample[premise]==0: continue 代码运行时提示这行报错,错误类型如标题。rn百度上查了好久,感觉没有给sample这个类定义getitem,具体操作应该怎么做?拜托大家了。
python测试类报错:AttributeError: module '__main__' has no attribute 'test_name_functi
初学python,编写一个函数的单元测试,然后报错如下:rnEErn======================================================================rnERROR: test_name_function (unittest.loader._FailedTest)rn----------------------------------------------------------------------rnAttributeError: module '__main__' has no attribute 'test_name_function'rnrn======================================================================rnERROR: true (unittest.loader._FailedTest)rn----------------------------------------------------------------------rnAttributeError: module '__main__' has no attribute 'true'rnrn----------------------------------------------------------------------rnrnname_function.py:rn[code=python]def get_formatted_name(first,last,middle=''):rn if middle:rn full_name = first+" "+middle+" "+last;rn else:rn full_name = first+" "+last;rn return full_name.title();rn[/code]rnrntest_name_function.pyrn[code=python]import unittestrnfrom ch02.owntest.name_function import get_formatted_namernclass NameTestCase(unittest.TestCase):rn def test_first_last_name(self):rn format_name = get_formatted_name('king','ivan')rn self.assertEqual(format_name,'King Ivan')rnrnunittest.main()[/code]rnrn运行这个test_name_function中unittest.main()就报上面错误,有谁知道怎么回事么
'NoneType' object has no attribute 'path'
用python3.5+selenium+firefox49.0 练习自动化测试rn以下是代码内容rnrn#coding=utf-8rnfrom selenium import webdriverrnrndriver = webdriver.Firefox()rndriver.get("http://www.baidu.com")rnrndriver.find_element_by_id("kw").send_keys("csdn")rndriver.find_element_by_id("su").click()rnrndriver.quit()rnrn执行成功了,没报错,但是报了这么个信息:rn'NoneType' object has no attribute 'path'rn查了好多资料啥的,都没个准确的方法,一开始我以为这个代码有问题,又写了别的用例,仍旧是能执行成功,但依然显示这个提示rn网上有些说是geckodriver没配置好,但是我是放到了python安装目录下的,python目录本身就在环境变量中,而且我用例也执行成功了rnrn哪位大神來指点一下?rn
'JSONDecoder' object has no attribute 'object_pairs_hook'
File "/usr/local/lib/python2.7/dist-packages/rklib-0.1.1_alpha-py2.7.egg/rklib/common/simplejson/decoder.py", line 322, in __init__rnrnAttributeError: 'JSONDecoder' object has no attribute 'object_pairs_hook'rnrn是否有兄台遇到过?rn版本的问题吗?
'Datasets' object has no attribute 'train_step'
import tensorflow as tfnfrom tensorflow.examples.tutorials.mnist import input_datanimport mnist_forwardnimport osnnBATAH_SIZE = 200nLEARNING_RATE_BASE = 0.1nLEARNING_RATE_DECAY = 0.99nREGULARIZER = 0.0001nSTEPS = 50000nMOVING_AVERAGE_DECAY = 0.99nMODEL_SAVE_PATH = "./model/"nMODEL_NAME = "mnist_model"nndef backward(mnist):nn x = tf.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE])n y_ = tf.placeholder(tf.float32, [None, mnist_forward.OUTPUT_NODE])n y = mnist_forward.forward(x, REGULARIZER)n global_step = tf.Variable(0, trainable=False)nn ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.arg_max(y_, 1))n cem = tf.reduce_mean(ce)n loss = cem + tf.add_n(tf.get_collection('losses'))nn learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step, mnist.train.num_examples / BATAH_SIZE,n LEARNING_RATE_DECAY, staircase=True)nn train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)nn ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)n ema_op = ema.apply(tf.trainable_variables())n with tf.control_dependencies([train_step, ema_op]):n train_op = tf.no_op(name='train')nn saver = tf.train.Saver()nn with tf.Session() as sess:n init_op = tf.global_variables_initializer()n sess.run(init_op)nn for i in range(STEPS):n xs, ys = mnist.train_step.next_batch(BATAH_SIZE)n _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict=x: xs, y_: ys)n if i % 1000 == 0:n print("After %d training step(s), loss on training batch is %g." % (step, loss_value))n saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)nndef main():n mnist = input_data.read_data_sets("./data/", one_hot=True)n backward(mnist)nnif __name__ == '__main__':n main()nn运行程序后报错:nn File "C:/Users/98382/PycharmProjects/minst/mnist_backward.py", line 54, in n main()n File "C:/Users/98382/PycharmProjects/minst/mnist_backward.py", line 51, in mainn backward(mnist)n File "C:/Users/98382/PycharmProjects/minst/mnist_backward.py", line 43, in backwardn xs, ys = mnist.train_step.next_batch(BATAH_SIZE)nAttributeError: 'Datasets' object has no attribute 'train_step'nn
'NoneType' object has no attribute '__getitem__'
按照《Ubuntu12.04.2 OpenStack Grizzly 安装(Bridge)》进行openstack安装,在配置keystone的时候,总是出现如下错误:rn> bash keystone.shrn 'NoneType' object has no attribute '__getitem__'rnrn不知道错在了哪里?rnrn《Ubuntu12.04.2 OpenStack Grizzly 安装(Bridge)》rnhttp://www.chenshake.com/ubuntu12-04-2-installed-openstack-grizzly-bridge-mode
大神帮我看一下这个'str' object has no attribute 'say_hi'
[img=https://img-bbs.csdn.net/upload/201805/19/1526704589_446084.png][/img]
python报错has no attribute '__trunc__'
rn我想写一个在数组中可以交换元素句子,就是如果第i个空了的话下一个补上这种,不太会python。纯小白,不太知道怎么交换array里的元素rnfor i in xrange(self.job_slot):rn index1=irn index2=i+1rn a = self.job_slot[index2]rn self.job_slot[index1]=arn 报的错是JobSlot instance has no attribute '__trunc__'rn还有一个问题是还有一次调试的时候i+1出界了,不知道这种怎么解决,拜托各位大神了[img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/003/monkey/2.gif][/img]
django的问题 'module' object has no attribute 'thread'
运行之后老是报这个错:“'module' object has no attribute 'thread'”rnrn在网上查了下,说要删除thread.pyc这个文件,然后我就到python/lib下把那个文件删除了,可是问题依旧啊rnrn求指导!!!
glance image-list 'NoneType' object has no attribute '
我是安装了三个节点的openstack,控制节点,计算节点,存储节点rn没有安装Neutron。也就只有这一点和《openstack实战指南》不一样rn然后当我运行glance image-list后出现了这个错误rnroot@ubuntu-controller:/# glance image-listrn'NoneType' object has no attribute 'rfind'rn请问有没有人遇到过,帮帮我吧,都卡这里好几天了。。。。rnrnps;我还没有添加镜像到数据库中,添加镜像的时候也是报这个错误rn
相关热词 c# login 居中 c# 考试软件 c# 自然语言分析 c# 分段读取文件 c# 泛型反射 c#打断点 c# 时间转多少秒 c# 线程函数加参数 c# modbus 读取 c#查询集合表