标签: attributeerror

AttributeError:'tuple'对象没有属性'write'

我有一个Python类的作业,我遇到了一个我不理解的错误.在Windows 7上运行Python IDLE v3.2.2.

以下是问题发生的地方:

#local variables
number=0
item=''
cost=''

#prompt user how many entries
number=int(input('\nHow many items to add?: '))

#open file
openfile=('test.txt','w')

#starts for loop to write new lines
for count in range(1,number+1):
    print('\nFor item #',count,'.',sep='')
    item=input('Name:  ')
    cost=float(input('Cost: $'))

    #write to file
    openfile.write(item+'\n')
    openfile.write(cost+'\n')

#Display message and closes file
print('Records written to test.txt.',sep='')
openfile.close
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

回溯(最近调用最后一次):文件"I:\ Cent 110\test.py",第19行,在openfile.write(item +'\n')中
AttributeError:'tuple'对象没有属性'write'

python tuples attributeerror

6
推荐指数
1
解决办法
3万
查看次数

AttributeError:'NoneType'对象没有属性'open_session'"

运行以下功能时:

def conEnclosure():
    freebay = open("freebay", "w+")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    password = getpass.getpass("Enter the password for infra: ")

    for host in open("full.json", "r"):
        print host
        ssh.connect("%s" % host, username="infra", password="%s" % password)
        stdin, stdout, stderr = ssh.exec_command("show server info all")
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

    Traceback (most recent call last):
  File "./findbay_v2.py", line 53, in <module>
    conEnclosure()
  File "./findbay_v2.py", line 41, in conEnclosure
    ssh.exec_command("show server info all")
  File "build/bdist.macosx-10.9-intel/egg/paramiko/client.py", line 364, in exec_command
AttributeError: 'NoneType' object has no attribute 'open_session'
Run Code Online (Sandbox Code Playgroud)

但是,在python shell中运行时,请执行以下命令:

>>> …
Run Code Online (Sandbox Code Playgroud)

python ssh paramiko attributeerror

6
推荐指数
1
解决办法
8461
查看次数

AttributeError:'_ io.TextIOWrapper'对象没有属性'lower'

我试图运行堆栈溢出是提供了一个示例在这里.

我在这里再次复制了代码:

from sklearn.feature_extraction.text import TfidfVectorizer
text_files = ['file1.txt', 'file2.txt']
documents = [open(f) for f in text_files]
tfidf = TfidfVectorizer().fit_transform(documents)
# no need to normalize, since Vectorizer will return normalized tf-idf
pairwise_similarity = tfidf * tfidf.T
Run Code Online (Sandbox Code Playgroud)

我添加的唯一内容就是这一行:

text_files = ['file1.txt', 'file2.txt']
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我收到此错误:

File "C:\Python33\lib\site-packages\sklearn\feature_extraction\text.py", line 195, in <lambda>
return lambda x: strip_accents(x.lower())
AttributeError: '_io.TextIOWrapper' object has no attribute 'lower'
Run Code Online (Sandbox Code Playgroud)

file1.txtfile2.txt输入的文本文件.我使用了错误的格式text_files吗?这个错误的原因是什么,我该如何解决?我真的很感激任何帮助.

python attributeerror scikit-learn

6
推荐指数
1
解决办法
6245
查看次数

具有格式化程序的Python日志记录模块会导致AttributeError

我正在编写一个终端应用程序,在传入-v选项之后,毫不奇怪地得到了详细信息.我想在终端中提供输出,以便于测试(无论如何,当它作为cron运行时,它会被重定向到日志文件).

但是,python logging模块不允许我在使用格式化程序时写出具有相应级别的消息.(格式化程序直接从Python Logging Cookbok复制)

此行为不仅限于Python3.Python2.7在给定条件下引发相同的异常.


one.py

from sys import stdout
import logging

if __name__ == '__main__':

    level = 20

    log = logging.getLogger()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler = logging.StreamHandler(stdout).setFormatter(formatter)
    log.addHandler(handler)
    log.setLevel(level)

    log.info("Blah")
Run Code Online (Sandbox Code Playgroud)

one.py输出

Traceback (most recent call last):
  File "/home/tlevi/PycharmProjects/untitled/main.py", line 14, in <module>
    log.info("Blah")
  File "/usr/lib/python3.4/logging/__init__.py", line 1279, in info
    self._log(INFO, msg, args, **kwargs)
  File "/usr/lib/python3.4/logging/__init__.py", line 1414, in _log
    self.handle(record)
  File "/usr/lib/python3.4/logging/__init__.py", line 1424, in handle
    self.callHandlers(record) …
Run Code Online (Sandbox Code Playgroud)

python logging stdout standard-library attributeerror

6
推荐指数
1
解决办法
1万
查看次数

AttributeError:'module'对象没有属性'cbook'

我正在尝试运行一个简单的代码,我在我的Canopy中安装了matplotlib和numpy的所有依赖项.我仍然得到错误.

    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    x = cv2.imread('jay.jpg')
    plt.imshow(x, cmap = 'gray', interpolation = 'bicubic')
    plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
    plt.show()
Run Code Online (Sandbox Code Playgroud)

错误:

     %run "c:\users\jay\appdata\local\temp\tmppvibq9.py"
     ---------------------------------------------------------------------------
     AttributeError                            Traceback (most recent call last)
     c:\users\jay\appdata\local\temp\tmppvibq9.py in <module>()
     2 import numpy as np
     3 import matplotlib.cbook
     ----> 4 import matplotlib.pyplot as plt
     5 
     6 x = cv2.imread('jay.jpg')

     C:\Users\Jay\AppData\Local\Enthought\Canopy\System\Lib\site-packages\matplotlib\pyplot.py in <module>()
     27 from cycler import cycler
     28 import matplotlib
     ---> 29 import …
Run Code Online (Sandbox Code Playgroud)

python matplotlib attributeerror canopy

6
推荐指数
2
解决办法
1万
查看次数

Scrapy shell返回无响应

我在使用 scrapy 抓取网站时遇到了一些问题。我按照 scrapy 的教程学习如何抓取网站,我有兴趣在网站“ https://www.leboncoin.fr ”上测试它,但蜘蛛不起作用。所以,我尝试过:

scrapy shell 'https://www.leboncoin.fr'
Run Code Online (Sandbox Code Playgroud)

但是,我没有得到该网站的回应。

$ scrapy shell 'https://www.leboncoin.fr'
2017-05-16 08:31:26 [scrapy.utils.log] INFO: Scrapy 1.3.3 started (bot: all_cote)
2017-05-16 08:31:26 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'all_cote', 'DUPEFILTER_CLASS':    'scrapy.dupefilters.BaseDupeFilter', 'LOGSTATS_INTERVAL': 0,   'NEWSPIDER_MODULE': 'all_cote.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['all_cote.spiders']}
2017-05-16 08:31:27 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole']
2017-05-16 08:31:27 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-05-16 08:31:27 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware'] …
Run Code Online (Sandbox Code Playgroud)

python attributeerror python-3.x scrapy-shell

6
推荐指数
1
解决办法
3384
查看次数

AttributeError:模块'tensorflow.python.estimator.estimator_lib'没有属性'LinearRegressor'

import tensorflow as tf
import numpy as np
feature_columns = [tf.feature_column.numeric_column("x", shape=[1])]
estimator = tf.estimator.LinearRegressor(feature_columns=feature_columns)
Run Code Online (Sandbox Code Playgroud)

我的代码在上面.然后它显示错误

"AttributeError:module'tensorflow.python.estimator.estimator_lib'没有属性'LinearRegressor'"

Python 3.5.2

attributeerror python-3.x tensorflow

6
推荐指数
1
解决办法
1万
查看次数

AttributeError:模块“spacy”没有属性“load”

import spacy
nlp = spacy.load('en_core_web_sm')

**Error:** Traceback (most recent call last):

  File "C:\Users\PavanKumar\.spyder-py3\ExcelML.py", line 27, in <module>
    nlp = spacy.load('en_core_web_sm')

AttributeError: module 'spacy' has no attribute 'load'
Run Code Online (Sandbox Code Playgroud)

有人能给我建议一个解决方案吗?

python attributes load attributeerror spacy-3

6
推荐指数
2
解决办法
9536
查看次数

AttributeError:模块“numpy.random”在 python 3.8.10 中没有属性“BitGenerator”

我试图将 xarray 模块导入 python 3.8.10 但出现此错误:

AttributeError: module 'numpy.random' has no attribute 'BitGenerator'

为了让您重现错误:首先,我使用 conda 创建了一个新环境,并同时导入了我需要的模块(以避免依赖项不兼容的问题):

conda create -n Myenv Python=3.8 matplotlib numpy time xarray netCDF4 termcolor

然后,我尝试在 ipython3 中导入运行代码所需的所有模块:

import matplotlib as mpl
mpl.use('agg')
import numpy as np
import os
import time
import glob
import sys
from datetime import datetime,date,timedelta
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import matplotlib.colors as colors
# from operator import itemgetter
from netCDF4 import Dataset
from mpl_toolkits.basemap import Basemap, shiftgrid
from termcolor import …
Run Code Online (Sandbox Code Playgroud)

numpy python-module attributeerror python-3.x python-xarray

6
推荐指数
1
解决办法
2万
查看次数

异常 AttributeError:“'NoneType' 对象没有属性 'path'”

我正在调试 python 代码(python2.7.12),因为我的代码可以工作,但是当我将推文流式传输到数据库时,所有变量都为 NULL。

我得到的错误是:

Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x10068f140> ignored
Run Code Online (Sandbox Code Playgroud)

我假设这个错误来自下面的代码:

def put_tweets_in_database(tweets):
    print "putting tweets in database"
    errors = 0
    count = 0

    for tweet in tweets:
        try:
            commit_tweet_to_database(tweet, count, len(tweets))
            count += 1  
        except Exception as e:
            print e
            session.rollback()
            errors += 1
    print 'there were {} errors'.format(errors)
Run Code Online (Sandbox Code Playgroud)

我不认为这个功能commit_tweet_to_database()有问题...

你有什么主意吗...?我将不胜感激任何帮助!

谢谢。

attributeerror python-2.7 try-except

5
推荐指数
1
解决办法
2万
查看次数