属性错误:“list”对象没有属性“split”

2024-04-25 22:10:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

time,latitude,longitude,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,earthquake

我的程序:

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()

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

"AttributeError: 'list' object has no attribute 'split'

请帮帮我!


Tags: 文件程序信息timetypefilenamesplit逗号
2条回答

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

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

我认为你实际上有更大的困惑。

最初的错误是试图调用整个行列表中的split,而不能split一个字符串列表,只能调用一个字符串。所以,你需要split每一行,而不是整行。

然后你在做for points in Type,期望每一个这样的points给你一个新的xy。但那不会发生的。Types只是两个值,xy,所以首先pointsx,然后点是y,然后就完成了。因此,同样,您需要循环每一行,并从每一行的中获取xy值,而不是从一行循环单个Types

所以,所有的东西都必须在文件中的每一行上进入一个循环,并对每一行执行一次splitxy的操作。像这样:

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,这些库确实为您提供了一种在整个数组或数据帧上隐式映射功能的方法,几乎与您尝试的方法相同。

相关问题 更多 >