属性错误:' list'对象没有属性' split'

时间:2015-05-05 00:30:11

标签: python list split turtle-graphics

我正在尝试读取文件并用逗号分割每行中的单元格,然后仅显示包含纬度和经度信息的第一个和第二个单元格。 这是文件:

  

时间,的纬度,经度下,type2015-03-20T10:20:35.890Z,的 38.8221664,-122.7649994 下,earthquake2015-03-20T10:18:13.070Z,的 33.2073333,-116.6891667 下,earthquake2015-03-20T10:15:09.000Z,的 62.242,-150.8769 下,地震

我的节目:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = readfile.readlines()

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()

当我尝试执行此程序时,它会给我一个错误

  

"属性错误:' list'对象没有属性' split'

请帮帮我!

3 个答案:

答案 0 :(得分:10)

我认为你实际上在这里遇到了更大的困惑。

最初的错误是你试图在整个行列表上调用split,而你不能split一个字符串列表,只能是一个字符串。因此,您需要split 每行,而不是整个行。

然后你正在做for points in Type,并期望每个points为你提供一个新的xy。但这不会发生。 Types只有两个值,xy,因此首先pointsx,然后点数为y,然后你会完成的。因此,您需要循环遍历每一行并从每行获取xy值,而不是从单个Types循环线。

因此,所有内容都必须在文件中的每一行内循环,并为每一行split xy执行一次。像这样:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")

    for line in readfile:
        Type = line.split(",")
        x = Type[1]
        y = Type[2]
        print(x,y)

getQuakeData()

作为旁注,你真的应该close该文件,理想情况下应该使用with语句,但最后我会谈到它。

有趣的是,这里的问题不是你是一个新手太多,而是你试图以专家的抽象方式解决问题,而且还不知道细节。这是完全可行的;你只需要明确地映射功能,而不是隐式地做。像这样:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = readfile.readlines()
    Types = [line.split(",") for line in readlines]
    xs = [Type[1] for Type in Types]
    ys = [Type[2] for Type in Types]
    for x, y in zip(xs, ys):
        print(x,y)

getQuakeData()

或者,更好的写作方式可能是:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    # Use with to make sure the file gets closed
    with open(filename, "r") as readfile:
        # no need for readlines; the file is already an iterable of lines
        # also, using generator expressions means no extra copies
        types = (line.split(",") for line in readfile)
        # iterate tuples, instead of two separate iterables, so no need for zip
        xys = ((type[1], type[2]) for type in types)
        for x, y in xys:
            print(x,y)

getQuakeData()

最后,您可能想看看NumPy和Pandas,的库为您提供了一种方法,可以在整个数组或数据框架上隐式映射功能,几乎与您尝试的方式相同到。

答案 1 :(得分:0)

问题是readlines是一个字符串列表,每个字符串都是一行filename。也许你的意思是:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

答案 2 :(得分:0)

通过将readlines转换为字符串,我做了一个快速修复,但是我不重新启动它,但是它可以正常工作,我不知道是否存在限制

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`
相关问题