我想要什么:
假设我使用OR运算符给一个变量两个字符串。比如:
command = 'windows go to books in d drive' or
'windows open books folder in d drive' or
'windows go to books which is in d drive'
我想从这里得到一个单词,即使用python中的regex模块从任意三个字符串中得到“books”
我尝试过的:
import re
import os
command = 'windows go to books in d drive' or 'windows open books folder in d drive' or 'windows go to books which is in d drive'
if 'windows go to' or 'windows open' in command:
non_greedy0 = re.compile(r'([go to ](.*?)[ in])|([go to ](.*?)[ folder])')
output0 = non_greedy0.findall(command)
print(output0)
tuple0 =output0[0]
print(tuple0)
subfolder = tuple0[0]
print(subfolder)
foo = 'D' + ':/' + str(subfolder)
os.startfile(foo)
输出:
[('ows ', 'ws', '', ''), ('go ', 'o', '', ''), ('to ', 'o', '', ''), ('ooks ', 'oks', '', ''), (' d ', 'd', '', '')]
('ows ', 'ws', '', '')
ows
File "***", line **, in <module> os.startfile(foo)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'D:/ows '
我更改了一些代码:
or
不是这样使用的or
不随机选择;它选择第一个非空字符串random.choice
随机选择李>[]
表示“组中的任何字符”,这不是您想要的:您想要完全匹配。而且您的正则表达式与“windows打开…”不匹配''.join(tuple0)
。这是因为tuple0
的长度为3(因为正则表达式中有3对括号),并且2项必须是空字符串''.join
通过连接三个字符串来解决问题李>相关问题 更多 >
编程相关推荐