我是一个初学者编码和项目,我有需要我分类一个文本文件。 我打开的txt文件是这样的: (这并不是txt文件看起来的样子,只是当我复制并通过它时,它看起来太乱了。因为某种原因,在另一个专栏里只写了“地图”一词)
MAG UTC DATE-TIME LAT LON DEPTH Region 4.3 2014/03/12 20:16:59 25.423 -109.730 10.0 GULF OF CALIFORNIA 5.2 2014/03/12 20:09:55 36.747 144.050 24.2 JAPAN 5.0 2014/03/12 20:08:25 35.775 141.893 24.5 JAPAN 4.8 2014/03/12 19:59:01 38.101 142.840 17.6 Japan 4.6 2014/03/12 19:55:28 37.400 142.384 24.7 JAPAN 5.0 2014/03/12 19:45:19 -6.187 154.385 62.0 GUINEA
我希望输出是这样的:
[[japan,'4.3','5.2','5.0','4.8','4.6'],[Gulf of California,4.3],[Guinea,5.0]]
我当前的编码: (第一个for循环中的vlist[7:]给出了区域名称,第二个for循环中的j[1]给出了mactitude编号。)
def myOpen(filepointer):
header = filepointer.readline()
regions = []#gathers up all the names of the regions without repeating them
maglist = []#matchs with naems and numbers
filelines = []#list of lines in txt file
for aline in filepointer:#reades each line
vlist = aline.split()#turns lines into lists
filelines.append(vlist)
if not vlist[7:] in regions:#makes list of names without repeat
regions.append(vlist[7:])
regions.sort()
for j in filelines:#gets each file line
for names in regions:#each name
if names == j[7:]:
num = j[1]
names.append(float(num))
mags.append(names)
return maglist
def main():
myFile = open('earthquakes.txt','r')
quakes = myOpen(myFile)
myFile.close()
print(quakes)
main()
给出以下输出:
[[japan,'4.3'],[Gulf of California,4.3],[Guinea,5.0]]
我想知道为什么它只得到其他区域出现的第一个震级数,而不是其他区域。你知道吗
给你:使用
itertools.groupby
、lambda
、map
、str.split
、str.lower
和str.join
如果您的文件如下所示:
以下是工作代码:
我来解释一下:
相关问题 更多 >
编程相关推荐