簡體   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