首页 > 解决方案 > Python解释器出现错误“AttributeError:'list'对象没有属性'split'”

问题描述

当我偶然发现一些奇怪的东西时,我正在使用 Python 3.6 编写编程语言。使用以下代码,我得到一个错误,并带有一些有趣的输出。

import sys
import tkinter as tk
import datetime

class _Viper:
    def __init__(self):
        pass
    def error(self, err, title="ERROR"):
        root = tk.Tk()
        root.title(title)
        root["bg"] = "#d56916"
        label = tk.Label(root, text=err)
        labelt = tk.Label(root, text=str(datetime.datetime.now()))
        label.config(bg="#e67a27")
        labelt.config(bg="#d56916")
        label.grid()
        labelt.grid()
        root.mainloop()
    def grabdata(self, line):
        raw = line.split("(")
        raw[1] = raw[1][:-1]
        print(type(raw[1]))
        raw[1] = raw[1].split()
        #raw[1] = raw[1].split('"')
        return {
            "keyword" : raw[0],
            "params"  : raw[1].split()
        }

Viper = _Viper() #For PyLint
"""
try:
    sys.argv[1]
    execute = True
except:
    execute = False
    Viper.error("Error `Viper.FileNotProvidedError` @ interpreter.py. Do not directly run this file. Run it with `Viper0.0.0a C:\\path\\to\\file`, or associate viper to Viper0.0.0a.bat.")
"""

sys.argv.append("C:\\viper\\interpreter\\testie.vi")
execute = True

if execute:
    extension = str(sys.argv[1][-2]+sys.argv[1][-1])
    if extension.upper() == "VI":
        with open("C:\\viper\\interpreter\\testie.vi", "r") as src:
            lines = src.readlines()
        for line in lines:
            Viper.grabdata(line)
    else:
        Viper.error("Error `Viper.ExtensionNotViperError` @ interpreter.py. Please run this with a file with the \"vi\" extension.")

运行此程序后,我收到此错误。 错误

你看到我看到的了吗?<class 'str'>是 的类raw[1]。那里空无一物。但是当我之后提到它时,它说它是一个列表!

有人能告诉我这里发生了什么吗?

编辑

我忘了添加毒蛇文件。

setvar("hmm", "No")

编辑 2

我将解释我的问题。它将字符串视为list

标签: pythonpython-3.6interpreter

解决方案


打印类型后的行:

 raw[1] = raw[1].split()

这会将其变成一个列表。当您raw[1]稍后使用调用时"params" : raw[1].split(),它不再是字符串,而是列表。所以这意味着raw[1]被拆分两次。如果您打算将参数raw[1]作为列表返回,则可以删除该行raw[1] = raw[1].split()


推荐阅读