我如何分割或切片括号内的所有内容,仍然循环通过?

2024-10-04 07:36:46 发布

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

当给定这样的字符串时,我必须拆分和切片此文本:

big_str = "[41.386263640000003, -81.494450689999994]    6    2011-08-28 19:02:28    yay. little league world series!\n[42.531041999999999, -82.90854831]    6    2011-08-28 19:02:29    i'm at holiday inn express suites & hotel roseville mi (31900 little mack ave., at masonic blvd., roseville)\n[39.992309570000003, -75.131119729999995]    6    2011-08-28 19:02:29    @_tweetthis what dorm r you in?\n[54.104106119999997, 28.336019929999999]    6    2011-08-28 19:02:29    @andykozik круто !!!\n[25.787949600000001, -80.132949600000003]    5    2011-09-03 05:40:14    pizza rustica #ftw"

我是这样做的:

def getLatitude(l):
  for x in l:
    y = list(x.split("\t"))
    for h in y:
        j = list(h.split("]"))
        w = j[0]
        x = len(w)/2
        v = w[1:x-1]
        z = float(v)
        return z
        continue

def getLongitude(x):
  y = list(x.split("\t"))
  w = y[0]
  x = len(w)/2
  v = w[x+1:-1]
  z = float(v)
  return z

def getGpsPixelX(x):
  y = (getLongitude(x) + 180) * 500.0/360
  return y

def getGpsPixelY(y):
  x = 500 - ((getLatitude(y) + 180) * 500.0/360)
  return x

line_list = big_str.split("\n")
getGpsPixelY(line_list)

我只需要将括号中的数字返回到getGpsPixelXY,所以我尝试了拼接和拆分,但当我放置两个拆分时,它有时会在get Latitude函数上显示错误…不仅如此,它只会给出第一行的值,而不会给出帖子的其他行的值。我不知道为什么,因为这是一个for循环


Tags: inforlenreturndeffloatatlist
1条回答
网友
1楼 · 发布于 2024-10-04 07:36:46

使用正则表达式:

例如:

import re
import ast
big_str = "[41.386263640000003, -81.494450689999994]    6    2011-08-28 19:02:28    yay. little league world series!\n[42.531041999999999, -82.90854831]    6    2011-08-28 19:02:29    i'm at holiday inn express suites & hotel roseville mi (31900 little mack ave., at masonic blvd., roseville)\n[39.992309570000003, -75.131119729999995]    6    2011-08-28 19:02:29    @_tweetthis what dorm r you in?\n[54.104106119999997, 28.336019929999999]    6    2011-08-28 19:02:29    @andykozik круто !!!\n[25.787949600000001, -80.132949600000003]    5    2011-09-03 05:40:14    pizza rustica #ftw"
res = []
for i in re.findall(r'\[.*?\]', big_str):
    res.extend(ast.literal_eval(i))
print(res)

输出:

[41.38626364, -81.49445069, 42.531042, -82.90854831, 39.99230957, -75.13111973, 54.10410612, 28.33601993, 25.7879496, -80.1329496]

相关问题 更多 >