繁体   English   中英

使用“ re.findall”分割字符串时出错

[英]error in splitting a string using “re.findall”

我需要将字符串分成三个值(x,y,z),字符串是这样的(48,25,19)

我使用“ re.findall” ,它工作正常,但有时会产生此错误

(plane_X, plane_Y, plane_Z = re.findall("\\d+.\\d+", planepos)

ValueError: not enough values to unpack (expected 3, got 0))

这是代码:



    def read_data():
        # reading from file
        file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/PlanePos.txt", "r")
        planepos = file.readline()
        file.close()
        file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/AirportPosition.txt", "r")
        airportpos = file.readline()
        file.close()
        # ==================================================================
        # spliting and getting numbers
        plane_X, plane_Y, plane_Z = re.findall("\d+\.\d+", planepos)
        airport_X, airport_Y, airport_Z = re.findall("\d+\.\d+", airportpos)
        return plane_X,plane_Y,plane_Z,airport_X,airport_Y,airport_Z

我需要的是将字符串(48,25,19) 拆分x = 48,y = 25,z = 19,因此如果有人知道更好的方法或解决此错误,将不胜感激。

您可以使用ast.literal_eval来安全地评估您的字符串:

import ast

s = '(48,25,19)'
x, y, z = ast.literal_eval(s)

# x => 48
# y => 25
# z => 19

您的正则表达式仅适用于带小数点的数字,不适用于整数,因此会出现错误。 您可以改为去除括号和空格的字符串,然后用逗号将字符串分开,然后将得到的字符串序列映射到float构造函数:

x, y, z = map(float, planepos.strip('() \n').split(','))

如果您的数字是整数,则可以使用正则表达式:

re.findall(r"\d+","(48,25,19)")                                         
['48', '25', '19']

如果有混数:

re.findall(r"\d+(?:\.\d+)?","(48.2,25,19.1)")                           
['48.2', '25', '19.1']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM