簡體   English   中英

從字符串中提取xyz坐標值到列表中

[英]Extracting xyz coordinate values from a string into lists

我有一些數據以字符串形式從格式如下所示的文件中獲取。 我想做的是創建一個向量(存儲為python中的列表),該向量指示對於每行的[x2,y2,z2]和[x1,x2,x3]在x,y,z方向上的差異。字符串如下所示。

一旦我將所需的[x2,y2,z2]和[x1,x2,x3]提取為整數列表,我就應該可以很好地計算差值向量。 我需要幫助的是根據下面的數據創建這些[x2,y2,z2]和[x1,x2,x3]列表。

data = """x1=45 y1=74 z1=55 col1=[255, 255, 255] x2=46 y2=74 z2=55 col2=[255, 255, 255] 
x1=34 y1=12 z1=15 col1=[255, 255, 255] x2=35 y2=12 z2=15 col2=[255, 255, 255] 
x1=22 y1=33 z1=24 col1=[255, 255, 255] x2=23 y2=33 z2=24 col2=[255, 255, 255] 
x1=16 y1=45 z1=58 col1=[255, 255, 255] x2=17 y2=45 z2=58 col2=[255, 255, 255] 
x1=27 y1=66 z1=21 col1=[255, 255, 255] x2=28 y2=66 z2=21 col2=[255, 255, 255]
"""

只是澄清一下,我只需要弄清楚如何為單行提取[x2,y2,z2]和[x1,x2,x3]列表。 我可以弄清楚如何為每條線循環並自己計算每條線的差向量。 它只是從每一行中提取相關數據並將其重新格式化為一種使我難受的可用格式。

我懷疑使用正則表達式是提取此信息的潛在途徑。 我查看了https://docs.python.org/2/library/re.html上的文檔,並對該文檔感到完全困惑和困惑。 我只想要一種易於理解的方法。

對於單行,假設所有行都具有相同的格式,則可以執行以下操作:

import re

a_line = "x1=45 y1=74 z1=55 col1=[255, 255, 255] x2=46 y2=74 z2=55 col2=[255, 255, 255]" 
x1,y1,z1,x2,y2,z2 = list(map(int, re.findall(r'=(\d+)', a_line)))

要根據數據處理多板線:

for a_line in data.split("\n"):    
    if a_line:
        x1,y1,z1,x2,y2,z2 = list(map(int, re.findall(r'=(\d+)', a_line)))
        print(x1,y1,z1,x2,y2,z2)

得到:

45 74 55 46 74 55
34 12 15 35 12 15
22 33 24 23 33 24
16 45 58 17 45 58
27 66 21 28 66 21

我確切地知道你來自哪里。 直到昨天我才明白正則表達式,他們總是把我弄糊塗了。 但是,一旦您了解了它們,您就會意識到它們的力量。 這是您的問題的一種可能的解決方案。 我還將對正則表達式的工作方式有一個直觀的了解,以期減少正則表達式背后的困惑。

在下面的代碼中,我假設您一次處理一行,並且數據的格式始終相同。

# Example of just one line of the data
line = """x1=45 y1=74 z1=55 col1=[255, 255, 255] x2=46 y2=74 z2=55 col2=[255, 255, 255] """

# Extract the relevant x1, y1, z1 values, stored as a list of strings
p1 = re.findall(r"[x-z][1]=([\d]*)", line)

# Extract the relevant x2, y2, z2 values, stored as a list of strings
p2 = re.findall(r"[x-z][2]=([\d]*)", line)

# Convert the elements in each list from strings to integers
p1 = [int(x) for x in p1]
p2 = [int(x) for x in p2]

# Calculate difference vector (Im assuming this is what you're trying to do)
diff = [p2[i] - p1[i] for i in range(len(p2))]

關於正則表達式中的符號的簡要說明

# EXPLANATION OF THE REGEX. 
# Finds segments of strings that: 
#     [x-z]    start with a letter x,y, or z
#     [1]      followed by the number 1
#     =        followed by the equals sign
# 
#     But dont return any of that section of the string, only use that 
#     information to then extract the following values that we do actually want 
#
#     (        Return the parts of the string that have the following pattern, 
#              given that they were preceded by the previous pattern
# 
#     [\d]     contain only a numeric digit
#     *        keep proceeding forward if the current character is a digit
#     )        end of the pattern, now we can return the substring.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM