如何在python的正则表达式模块中获取以字符串开头、以字符串结尾的多个字符串?

2024-09-26 22:10:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要什么:

  • 假设我使用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 '

Tags: ortoingooswindowsdriveopen
1条回答
网友
1楼 · 发布于 2024-09-26 22:10:04
import re
import os
from random import choice

command = choice(['windows go to books in d drive', 
                  'windows open books folder in d drive', 
                  'windows go to books which is in d drive'])

if 'windows go to' or 'windows open' in command:
    non_greedy0 = re.compile('go to (.*?) (which is ){0,1}in')
    non_greedy1 = re.compile('go to (.*?) folder')
    non_greedy2 = re.compile('open (.*?) folder')

    output0 = non_greedy0.findall(command)
    output1 = non_greedy1.findall(command)
    output2 = non_greedy2.findall(command)
    print(output0, output1, output2)

    if output0 != []:
        tuple0 = output0[0]
    elif output1 != []:
        tuple0 = output1[0]
    elif output2 != []:
        tuple0 = output2[0]
    print(tuple0)

    subfolder = ''.join(tuple0)
    print(subfolder)

    foo = 'D:\\' + subfolder
    os.startfile(foo)

我更改了一些代码:

  1. 在Python中,or不是这样使用的or不随机选择;它选择第一个非空字符串random.choice随机选择
  2. 你用的正则表达式。regex中的[]表示“组中的任何字符”,这不是您想要的:您想要完全匹配。而且您的正则表达式与“windows打开…”不匹配
  3. 我用了三个正则表达式而不是一个。这使代码更易于理解。(而且更容易调试!)
  4. 为了找到子文件夹名,我使用了''.join(tuple0)。这是因为tuple0的长度为3(因为正则表达式中有3对括号),并且2项必须是空字符串''.join通过连接三个字符串来解决问题
  5. 在Windows中,反斜杠用作路径分隔符,而不是正斜杠

相关问题 更多 >

    热门问题