python - Python 将三行 .split() 合并为一行?
问题描述
我有这段代码,我希望三个拆分命令可以组合成一行,但我不知道如何:
from __future__ import print_function # Must be first import
import subprocess32 as sp
def get_mouse_coordinates():
''' Get mouse co-ordinates with xdotool:
$ xdotool getmouselocation
x:4490 y:1920 screen:0 window:65011722
'''
command_line_list = ['xdotool', 'getmouselocation']
pipe = sp.Popen(command_line_list, stdout=sp.PIPE, stderr=sp.PIPE)
text, err = pipe.communicate() # This performs .wait() too
print("returncode of subprocess:",pipe.returncode)
if text:
x, y, z = text.split(' ',2) # Grab 'x:9999' 'y:9999' 'junk'
x_ret = x.split(':')[1] # Grab right of 'x:9999'
y_ret = y.split(':')[1] # Grab right of 'y:9999'
print("standard output of subprocess:")
print(text,'x-offset:',x_ret,'y-offset:',y_ret)
return x_ret, y_ret
if err:
print("standard error of subprocess:")
print(err)
return 100, 100
可能很明显,但这些是三行代码:
x, y, z = text.split(' ',2) # Grab 'x:9999' 'y:9999' 'junk'
x_ret = x.split(':')[1] # Grab right of 'x:9999'
y_ret = y.split(':')[1] # Grab right of 'y:9999'
如果您好奇,请在终端中输出:
returncode of subprocess: 0
standard output of subprocess:
x:3400 y:558 screen:0 window:23073340
x-offset: 3400 y-offset: 558
解决方案
正如@zvone 提到的,一种方法是使用正则表达式。本质上,您只是想提取数字,因此模式非常简单:
import re
x, y, screen, window = re.findall("[0-9]+", text)
请注意,如果数字能够为负数,则您需要稍长的模式(但在您的情况下,它们似乎不会):
import re
x, y, screen, window = re.findall("[-+]?[0-9]+", text)
正则表达式模块的文档:https ://docs.python.org/3/library/re.html
您还可以使用列表推导:
x, y, screen, window = [tok.split(":")[1] for tok in text.split(" ")]
推荐阅读
- php - 在 Doctrine 中,如何忽略更新模式命令中的特定列?
- oracle-apex - 如何使用 SQLPLUS 导入 APEX 应用程序
- python - 通过隧道连接(通过 ssh)连接 jupyter python
- react-native - 在嵌套反应导航组件上使用 Jest 进行快照测试 - 对象键更改,因此快照匹配失败
- c# - 扩展 DbContext 以避免代码重复
- regex - nginx位置正则表达式多个元素
- linq - Entity Framework Core + 使用 Group By 计数
- swift - 如何声明具有两种可能类型的变量
- python - 如何检查字符串中的日期是否大于给定日期?蟒蛇 3
- php - 如何在php中序列化反序列化mongo文档?