[英]error in splitting a string using “re.findall”
i need to split a string into three values (x,y,z) the string is something like this (48,25,19) 我需要将字符串分成三个值(x,y,z),字符串是这样的(48,25,19)
i used "re.findall" and it works fine but sometimes it produces this error 我使用“ re.findall” ,它工作正常,但有时会产生此错误
(plane_X, plane_Y, plane_Z = re.findall("\\d+.\\d+", planepos)
ValueError: not enough values to unpack (expected 3, got 0))
this is the code: 这是代码:
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
what i need is to split the string (48,25,19) to x=48,y=25,z=19 so if someone know a better way to do this or how to solve this error will be appreciated. 我需要的是将字符串(48,25,19) 拆分为x = 48,y = 25,z = 19,因此如果有人知道更好的方法或解决此错误,将不胜感激。
You can use ast.literal_eval
which safely evaluates your string: 您可以使用
ast.literal_eval
来安全地评估您的字符串:
import ast
s = '(48,25,19)'
x, y, z = ast.literal_eval(s)
# x => 48
# y => 25
# z => 19
Your regex only works for numbers with a decimal point and not for integers, hence the error. 您的正则表达式仅适用于带小数点的数字,不适用于整数,因此会出现错误。 You can instead strip the string of parentheses and white spaces, then split the string by commas, and map the resulting sequence of strings to the
float
constructor: 您可以改为去除括号和空格的字符串,然后用逗号将字符串分开,然后将得到的字符串序列映射到
float
构造函数:
x, y, z = map(float, planepos.strip('() \n').split(','))
If your numbers are integers, you can use the regex: 如果您的数字是整数,则可以使用正则表达式:
re.findall(r"\d+","(48,25,19)")
['48', '25', '19']
If there are mixed numbers: 如果有混数:
re.findall(r"\d+(?:\.\d+)?","(48.2,25,19.1)")
['48.2', '25', '19.1']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.