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

RPi*_*ess 6 python sqlite

我正在开发这个程序,出于某种原因,我不断收到这个错误。这是 Ubuntu 导致的错误,还是我的代码中的某些内容导致程序崩溃?

我正在访问数据库并尝试从输出中删除以下字符:和,通过value.translate(dictionary_of_bad_characters). 这就是我得到错误的地方。

def get_data(plu):          # Get the data needed
    global value            # Set the variable value to global

    conn = sqlite3.connect('plus.sqlite')   # Connect to the sqlite3 database

    cursor = conn.cursor()  # Set cursor as the cursor for plus.sqlite

    results = cursor.execute('SELECT value FROM plus WHERE plu=?', [plu])
    # Above code gets the data value for value with the PLU of plu

    value = results.fetchone()            # Get the results of value

    data = [row[0] for row in results.fetchall()]

    translation_table = dict.fromkeys(map(ord, '+-(),'), None)
    # Above code creates a table with the mapped characters

    value = value.translate(translation_table)
    # Above code removes any unnescessary characters from value

    response = {    'PLU':      plu,
                    'Value':    value
                    }       # Create the response variable

    value = int(value)      # Convert value to type integer

    cursor.close()          # Close the cursor
    conn.close()            # Close the connection

    return(value)           # Return to the program flow
Run Code Online (Sandbox Code Playgroud)

And*_*ini 8

此错误表明这value是一个元组,而不是您可能期望的字符串。这表明您的应用程序存在问题。

这里的问题是fetchone()返回一个单元组。你应该从这一行改变:

value = results.fetchone()
Run Code Online (Sandbox Code Playgroud)

对此(注意后面的逗号value):

value, = results.fetchone()
Run Code Online (Sandbox Code Playgroud)

或者这个(不推荐):

value = results.fetchone()[0]
Run Code Online (Sandbox Code Playgroud)

但是为什么fetchone()返回一个元组而不是一个字符串?因为你可以SELECT多列。例如,考虑以下 SQL 语句:

SELECT a, b, c FROM my_table;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,fetchone()将返回一个三元组。

编写value, = fetchone()您是在告诉 Python 您期待一个单元组,并且您希望将单个项目放入value. 如果您期待三元组,您会使用column_a, column_b, column_c = resulsts.fetchone().

这就是为什么你应该更喜欢的原因value,fetchone()[0]


额外提示:我注意到您使用的是 Python 3。在这种情况下,您可以编写:

translation_table = dict.fromkeys(b'+-(),', None)
Run Code Online (Sandbox Code Playgroud)

加速您的代码并使其更干净。