从某个字符串中提取数字

问题描述

我有来自 pyautogui 模块的这个字符串: mouse_position = "Point(x=535,y=415)"

我只想获取 x 和 y 并将它们放在自己单独的变量中,例如 x = 535y = 415,但我不知道在哪里拆分字符串。我无法看到自己在不采取多个步骤的情况下拆分它们。

我尝试了 ext_int = [int(i) for i in mouse_position.split() if i.isdigit()],但我发现它没有按预期工作。也许除了拆分之外还有另一种提取它们的方法?任何提示将不胜感激。

解决方法

由于这些是字符串中唯一的数字,您可以使用简短的正则表达式将它们拉出:

import re

s = 'mouse_position = "Point(x=535,y=415)"'

[int(n) for n in re.findall(r'\d+',s)]
# [535,415]

这基本上是说,查找由 1 个或多个数字组成的所有字符串。请注意,您需要根据字符串中的顺序确定哪个是 x,哪个是 y。如果它可以是 Point(y=415,x=535),您将需要更复杂的东西。

,

你总是可以拿出真正的文本提取工具。正则表达式:

import re 

mouse_position = "Point(x=535,y=415)"

d = re.match("Point\(x=(?P<x>\d+),y=(?P<y>\d+)\)",mouse_position).groupdict()

d 现在是:

{'x': '535','y': '415'}
,

另一种使用 slicing 的方法:

s = 'mouse_position = "Point(x=535,y=415)"'
x_s=s.index('x=')+2
x_e=s.index(',')
x = int(s[x_s:x_e])

y_s=s.index('y=')+2
y_e=s.index(')')
y = int(s[y_s:y_e])

#print(f"{x=},{y=}")
print(x)#535
print(y)#415
,

这可能是最不像 Python 的代码,但它很容易理解,而且运行得非常好且速度极快

import pyautogui
import numpy as np

while True:
    original_string = str(pyautogui.position()) #getting the position of mouse
    characters_to_remove = "Point()xy=,:[]''" #characters you want to remove
    new_string = original_string
    for character in characters_to_remove:
        new_string = new_string.replace(character,"")
        a = new_string.split()
        b = np.array_split(a,2)
        c = str((a[0]))
        d = str((a[1]))

    for character in characters_to_remove:
       x = c.replace(character,"")
       y = d.replace(character,"")
    print(x + "," + y)