[英]Attribute Error: 'list' object has no attribute 'split'
我正在尝试读取一个文件并用逗号分割每行中的一个单元格,然后仅显示包含有关纬度和经度的信息的第一个和第二个单元格。 这是文件:
时间,纬度,经度,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()
当我尝试执行这个程序时,它给了我一个错误
“AttributeError: 'list' 对象没有属性 'split'
请帮我!
我认为你实际上在这里有更广泛的困惑。
最初的错误是您试图在整个行列表上调用split
,并且您不能split
字符串列表,只能split
字符串。 所以,你需要split
每一行,而不是整件事。
然后你正在做for points in Type
,并期望每个这样的points
给你一个新的x
和y
。 但这不会发生。 Types
只是两个值, x
和y
,所以第一个points
是x
,然后点是y
,然后你就完成了。 因此,同样,您需要遍历每一行并从每行获取x
和y
值,而不是从一行中遍历单个Types
。
因此,所有内容都必须在文件中的每一行上进行循环,并对每一行进行一次x
和y
split
。 像这样:
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,它们确实为您提供了一种隐式映射整个数组或数据帧的功能的方法,这与您尝试的方式几乎相同。
问题是readlines
是一个字符串列表,每个字符串都是一行filename
。 也许你的意思是:
for line in readlines:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
我所做的是通过将 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()`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.