【发布时间】:2022-01-23 10:45:19
【问题描述】:
import asyncio
import re
import time
from datetime import datetime
detection_timer = 0
detection_timer_increment = 5
detection_timer_change = 10
x, y , z = None, None, None
x_aux, y_aux, z_aux = 0, 0, 0
def get_coords(input_coords):
input_coords = input_coords.replace("@","0") #convierte todos los posibles caracteres @ en caracteres 0
m = re.match(r".*:\s*([0-9.]*?)\s*,\s*([0-9.]*?)\s*,\s*([0-9.]*?)$", input_coords) #No agarra los numeros negativos
if m:
return m.groups()
async def timer():
global x, y, z, x_aux, y_aux, z_aux
global input_coords
global detection_timer, detection_timer_change
detection_timer += detection_timer_increment
#Debe entrar a este if cara cierto tiempo
if(detection_timer >= detection_timer_change):
detection_timer = 0 #resetea contador
#detect_color()
r = get_coords(input_coords)
if r:
x_aux = x = float(r[0]) if r[0] else x
y_aux = y = float(r[1]) if r[1] else y
z_aux = z = float(r[2]) if r[2] else z
return x_aux, y_aux, z_aux
while True:
#Some examples of possible inputs
#input_coords = "Coordenadas: @, 63, -5|hhhf♀"
#input_coords = "Coordenadas: @, 63.5, -5.695|hhhf♀"
#input_coords = "Coordenadas: @, hhkjkm♀-63ss, -5|hhhf♀"
#input_coords = "Coordenadas: -8, 63, -5 \n♀"
input_coords = "Coordenadas: @, 63, -5"
x_aux, y_aux, z_aux = asyncio.run(timer())
if(x_aux != None and y_aux != None and z_aux != None):
print(x_aux)
print(y_aux)
print(z_aux)
虽然代码运行不好,但万一它们是负坐标或者字符串末尾有更多值。 我应该如何更正这个正则表达式,以便它可以捕获我在代码中输入的示例值?
“坐标:@, 63, -5|hhhf♀” ----> 这应该提取 0,63,-5
“坐标:@, 63.5, -5.695|hhhf♀” ----> 这应该提取 0,63.5,-5.695
“坐标:@, hhkjkm♀-63ss, -5|hhhf♀” ----> 这应该提取 0, -63, -5
"Coordenadas: -8, 63, -5 \n♀" ----> 这应该提取 -8,63,-5
"Coordenadas: @, 63, -5" ----> 这应该提取 0,63,-5
【问题讨论】:
-
第一个问题很好 - 感谢您花时间提供代码、示例和预期结果。
标签: python python-3.x regex string re