GVKun编程网logo

如何解决'str'在Python中没有属性'maketrans'错误?(python str没有decode)

17

此处将为大家介绍关于如何解决'str'在Python中没有属性'maketrans'错误?的详细内容,并且为您解答有关pythonstr没有decode的相关问题,此外,我们还将为您介绍关于'str'

此处将为大家介绍关于如何解决'str'在Python中没有属性'maketrans'错误?的详细内容,并且为您解答有关python str没有decode的相关问题,此外,我们还将为您介绍关于'str'对象在Python3中没有属性'decode'、'str'对象没有属性'decode'Python 3错误?、'str'对象没有属性'decode'。Python 3错误?、AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'的有用信息。

本文目录一览:

如何解决'str'在Python中没有属性'maketrans'错误?(python str没有decode)

如何解决'str'在Python中没有属性'maketrans'错误?(python str没有decode)

运行python proxy.py时出现错误

$ python proxy.py INFO - [Sep 28 14:59:19] getting appids from goagent plus common appid pool!Traceback (most recent call last):  File "proxy.py", line 2210, in <module>    main()  File "proxy.py", line 2180, in main    pre_start()  File "proxy.py", line 2157, in pre_start    common.set_appids(get_appids())  File "proxy.py", line 94, in get_appids    fly = bytes.maketrans(AttributeError: type object ''str'' has no attribute ''maketrans''

https://code.google.com/p/smartladder/中的proxy.py文件,

def get_appids():    fly = bytes.maketrans(        b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",        b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"    )    f = urllib.request.urlopen(url="http://lovejiani.com/v").read().translate(fly)    d = base64.b64decode(f)    e = str(d, encoding=''ascii'').split(''\r\n'')    random.shuffle(e)    return  e

答案1

小编典典

您正在使用Python 2运行为Python 3编写的代码。这将无法工作。

maketransbytes内置类型的类方法,但 仅在Python 3中

# Python 3>>> bytes<class ''bytes''>>>> bytes.maketrans<built-in method maketrans of type object at 0x10aa6fe70>

在Python 2,bytes是一个别名str,但该类型并 没有 有方法:

# Python 2.7>>> bytes<type ''str''>>>> bytes.maketransTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: type object ''str'' has no attribute ''maketrans''

而是使用Python 3运行您的代码,或将该项目中的所有代码转换为Python 2;后者需要深入了解Python 2和3的不同之处,这可能是一项重要的工作。

只是 翻译成Python 2的所示函数将是:

import stringimport urllib2import base64import randomdef get_appids():    fly = string.maketrans(        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",        "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"    )    f = urllib2.urlopen("http://lovejiani.com/v").read().translate(fly)    d = base64.b64decode(f)    e = unicode(d, encoding=''ascii'').split(u''\r\n'')    random.shuffle(e)    return e

'str'对象在Python3中没有属性'decode'

'str'对象在Python3中没有属性'decode'

我在python 3.3.4中遇到“解码”方法的问题。这是我的代码:

for lines in open(''file'',''r''):    decodedLine = lines.decode(''ISO-8859-1'')    line = decodedLine.split(''\t'')

但是我无法解码此问题的代码:

AttributeError: ''str'' object has no attribute ''decode''

你有什么想法?谢谢

答案1

小编典典

一种 编码 字符串,另一种 解码 字节。

您应该从文件中读取字节并对其进行解码:

for lines in open(''file'',''rb''):    decodedLine = lines.decode(''ISO-8859-1'')    line = decodedLine.split(''\t'')

幸运的是,open有一个编码参数使操作变得简单:

for decodedLine in open(''file'', ''r'', encoding=''ISO-8859-1''):    line = decodedLine.split(''\t'')

'str'对象没有属性'decode'Python 3错误?

'str'对象没有属性'decode'Python 3错误?

如何解决''str''对象没有属性''decode''Python 3错误??

您正在尝试解码 已解码 的对象。您有一个str,不再需要从UTF-8解码。

只需删除.decode(''utf-8'')部分:

header_data = data[1][0][1]

至于您的fetch()通话,您明确要求仅发送第一条消息。如果要检索更多消息,请使用范围。请参阅文档:

下面命令的 message_set 选项是一个字符串,用于指定要执行的一条或多条消息。它可以是简单的消息号(''1''),消息号的范围(''2:4'')或由逗号分隔的一组非连续范围(''1:3,6:9'')。一个范围可以包含一个星号,以指示一个无限的上限(''3:*'')。

解决方法

这是我的代码:

import imaplib
from email.parser import HeaderParser

conn = imaplib.IMAP4_SSL(''imap.gmail.com'')
conn.login(''example@gmail.com'',''password'')
conn.select()
conn.search(None,''ALL'')
data = conn.fetch(''1'',''(BODY[HEADER])'')
header_data = data[1][0][1].decode(''utf-8'')

此时,我收到错误消息

AttributeError: ''str'' object has no attribute ''decode''

Python 3不再具有解码了,对吗?我怎样才能解决这个问题?

另外,在:

data = conn.fetch(''1'',''(BODY[HEADER])'')

我只选择第一封电子邮件。如何选择全部?

'str'对象没有属性'decode'。Python 3错误?

'str'对象没有属性'decode'。Python 3错误?

这是我的代码:

import imaplibfrom email.parser import HeaderParserconn = imaplib.IMAP4_SSL(''imap.gmail.com'')conn.login(''example@gmail.com'', ''password'')conn.select()conn.search(None, ''ALL'')data = conn.fetch(''1'', ''(BODY[HEADER])'')header_data = data[1][0][1].decode(''utf-8'')

此时,我收到错误消息

AttributeError: ''str'' object has no attribute ''decode''

Python 3不再具有解码了,对吗?我怎样才能解决这个问题?

另外,在:

data = conn.fetch(''1'', ''(BODY[HEADER])'')

我只选择第一封电子邮件。如何选择全部?

答案1

小编典典

您正在尝试解码 已解码 的对象。您有一个str,不再需要从UTF-8解码。

只需删除.decode(''utf-8'')部分:

header_data = data[1][0][1]

至于您的fetch()通话,您明确要求仅发送第一条消息。如果要检索更多消息,请使用范围。请参阅文档:

下面命令的 message_set
选项是一个字符串,用于指定要执行的一条或多条消息。它可以是简单的消息号(''1''),消息号的范围(''2:4'')或由逗号分隔的一组非连续范围(''1:3,6:9'')。一个范围可以包含一个星号,以指示一个无限的上限(''3:*'')。

AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'

AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'

如何解决AttributeError: ''super'' 对象在 python 和 kivy 代码中没有属性 ''__getattr__''?

您好,我在使用 kivy 时遇到了这个错误。我的目的是创建我的应用程序的登录屏幕,用于检查用户输入的数据是否正确。但是这样做时,我一次又一次地收到此错误。



我的代码如下:

Python 文件:

from kivy.lang import Builder
from kivymd.app import MDApp  
import MysqL.connector as ms
from kivy.properties import StringProperty,NumericProperty
from kivy.uix.screenmanager import ScreenManager,Screen


acc = NumericProperty("")
pw = StringProperty("")

class safarapp(MDApp):
    def build(self):
        self.theme_cls.theme_Dark''
        self.theme_cls.primary_palette = ''BlueGray''
        return
        
    def Login(self):
            self.acc = self.root.ids.acc_num.text
            
            self.pw = self.root.ids.password.text
            
            host = ms.connect(
              host="localhost",user="root",password="bhawarth20",database="safar"
              )
              
            cur = host.cursor(buffered = True)
            
            
            
            cur.execute("Select * from data where Account_Number = %s and Password = %s collate utf8mb4_bin",(self.acc,self.pw))
            data="error" #initially just assign the value
            
            for i in cur:
                data=i #if cursor has no data then loop will not run and value of data will be ''error''
                if data== "error":
                    print("User Does not exist")
                else:
                    print("User exist")

class LoginScreen(Screen):
    pass
    
    
class SignUpScreen(Screen):
    pass


sm = ScreenManager()
sm.add_widget(LoginScreen(name= "login"))
sm.add_widget(SignUpScreen(name= "signup"))



                    
                    
if __name__ == ''__main__'':
    safarapp().run()

KV 文件:


ScreenManager:
    LoginScreen:
    SignUpScreen:


<LoginScreen>:
    name: ''login''
    MDCard:
        size_hint: None,None
        size: 300,400
        pos_hint: {''center_x'': .5,''center_y'': .5}
        elevation:10
        spacing: 25
        padding: 25
        orientation: ''vertical''
        
        MDLabel:
            text: "Safar Login"
            font_size: 40
            halign: ''center''
            size_hint_y: None
            height: self.texture_size[1]
            padding_y: 10
            pos_hint: {''center_y'': 1}

        MDTextField:
            id: acc_num
            hint_text: ''Account Number''
            icon_right: ''account''
            max_text_length: 6
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            font_size: 18
            required: True
                        
        MDTextField:
            id: password
            hint_text: ''Password''
            password: True
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            font_size: 18
            icon_right: ''eye''
            required: True
            
        MDFillRoundFlatButton:
            id: Login
            text: ''Login''
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            elevation: 10
            on_release: app.Login()

            
        MDFillRoundFlatButton:
            id: Sign_Up
            text: ''Sign Up''
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            elevation: 10
            on_release: root.manager.current = ''signup''
            
                
<SignUpScreen>:
    name: ''signup''
    MDLabel:
        text: "Hello World!!!"

这是我得到的错误:

[INFO   ] [Logger      ] Record log in C:\Users\Welcome\.kivy\logs\kivy_21-07-12_51.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO   ] [Kivy        ] v2.0.0
[INFO   ] [Kivy        ] Installed at "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\__init
py"
[INFO   ] [Python      ] v3.8.2 (tags/v3.8.2:7b3ab59,Feb 25 2020,22:45:29) [MSC v.1916 32 bit (Intel)]
[INFO   ] [Python      ] Interpreter at "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\python.exe"
[INFO   ] [Factory     ] 186 symbols loaded
[INFO   ] [KivyMD      ] 0.104.2,git-bc7d1f5,2021-06-06 (installed at "C:\Users\Welcome\AppData\Local\Programs\Python\python3
2\lib\site-packages\kivymd\__init__.py")
[INFO   ] [Image       ] Providers: img_tex,img_dds,img_sdl2,img_pil (img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [Window      ] Activate GLES2/ANGLE context
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] Backend used <angle_sdl2>
[INFO   ] [GL          ] OpenGL version <b''OpenGL ES 2.0.0 (ANGLE 2.1.13739 git hash: 385fb40fd460)''>
[INFO   ] [GL          ] OpenGL vendor <b''Google Inc.''>
[INFO   ] [GL          ] OpenGL renderer <b''ANGLE (Mobile Intel(R) 965 Express Chipset Family Direct3D11 vs_4_0 ps_4_0)''>
[INFO   ] [GL          ] OpenGL parsed version: 2,0
[INFO   ] [GL          ] Shading version <b''OpenGL ES GLSL ES 1.00 (ANGLE 2.1.13739 git hash: 385fb40fd460)''>
[INFO   ] [GL          ] Texture max size <8192>
[INFO   ] [GL          ] Texture max units <16>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed,single mode,not docked
[INFO   ] [GL          ] NPOT texture support is available
[INFO   ] [Base        ] Start application main loop
[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "kivy\properties.pyx",line 861,in kivy.properties.ObservableDict.__getattr__
 KeyError: ''acc_num''

 During handling of the above exception,another exception occurred:

 Traceback (most recent call last):
   File "D:\my projects of python\Safar\safar.py",line 69,in <module>
     safarapp().run()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\app.py",line 950,in run
     runTouchApp()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 582,in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 347,in mainloop
     self.idle()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 391,in idle
     self.dispatch_input()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 342,in dispatch_inpu
     post_dispatch_input(*pop(0))
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 308,in post_dispatch
put
     wid.dispatch(''on_touch_up'',me)
   File "kivy\_event.pyx",line 709,in kivy._event.Eventdispatcher.dispatch
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivymd\uix\behaviors\ripple_behavior.py",ne 296,in on_touch_up
     return super().on_touch_up(touch)
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivymd\uix\button.py",line 981,in on_to
_up
     return super().on_touch_up(touch)
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\uix\behaviors\button.py",line 179,on_touch_up
     self.dispatch(''on_release'')
   File "kivy\_event.pyx",line 705,in kivy._event.Eventdispatcher.dispatch
   File "kivy\_event.pyx",line 1248,in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx",line 1132,in kivy._event.EventObservers._dispatch
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\lang\builder.py",line 57,in custom
llback
     exec(__kvlang__.co_value,idmap)
   File "D:\my projects of python\Safar\safar.kv",line 56,in <module>
     on_release: app.Login()
   File "D:\my projects of python\Safar\safar.py",line 27,in Login
     self.acc = self.root.ids.acc_num.text
   File "kivy\properties.pyx",line 864,in kivy.properties.ObservableDict.__getattr__
 AttributeError: ''super'' object has no attribute ''__getattr__''

请帮助我尽快解决此错误。任何帮助将不胜感激。

解决方法

您的代码:

    self.acc = self.root.ids.acc_num.text
    self.pw = self.root.ids.password.text

正在尝试访问不在 ids root 字典中的 ids。这些 ids<LoginScreen>: 规则中定义,因此它们出现在 LoginScreen 实例中。将这两行替换为:

    login_screen = self.root.get_screen(''login'')
    self.acc = login_screen.ids.acc_num.text
    self.pw = login_screen.ids.password.text

今天关于如何解决'str'在Python中没有属性'maketrans'错误?python str没有decode的讲解已经结束,谢谢您的阅读,如果想了解更多关于'str'对象在Python3中没有属性'decode'、'str'对象没有属性'decode'Python 3错误?、'str'对象没有属性'decode'。Python 3错误?、AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'的相关知识,请在本站搜索。

本文标签: