[英]Extract numbers from a certain string
我有来自pyautogui
模块的这个字符串: mouse_position = "Point(x=535, y=415)"
我只想得到 x 和 y 并将它们放在他们自己的单独变量中,例如x = 535
和y = 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.