Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 拆分文本包含空格,但将引号内的单词作为一个单元保留_Python_Regex - Fatal编程技术网

Python 拆分文本包含空格,但将引号内的单词作为一个单元保留

Python 拆分文本包含空格,但将引号内的单词作为一个单元保留,python,regex,Python,Regex,我想将文本拆分为列表,其中带空格的文件名应被视为单个项:示例 s = 'cmd -a -b -c "file with spaces.mp4" -e -f'.split() print(s) 输出: ['cmd', '-a', '-b', '-c', '"file', 'with', 'spaces.mp4"', '-e', '-f'] 期望输出: ['cmd', '-a', '-b', '-c', '"file with spaces.mp4"', '-e', '-f'] 我尝试过使用一

我想将文本拆分为列表,其中带空格的文件名应被视为单个项:示例

s = 'cmd -a -b -c "file with spaces.mp4" -e -f'.split()
print(s)
输出:

['cmd', '-a', '-b', '-c', '"file', 'with', 'spaces.mp4"', '-e', '-f']
期望输出:

['cmd', '-a', '-b', '-c', '"file with spaces.mp4"', '-e', '-f']

我尝试过使用一些for循环,但它变得很糟糕,有没有合适的方法使用regex或其他看起来不难看的东西呢

  • 最后接另一个
    “[^”]*”
    ),或
  • 任何非空格字符(
    \S+
    ):

实际上,在这种情况下,我不会使用正则表达式。这就是它的用途:

印刷品:

['cmd', '-a', '-b', '-c', 'file with spaces.mp4', '-e', '-f']
试一试

产量

['cmd', '-a', '-b', '-c', 'file with spaces.mp4', '-e', '-f']

这可以通过内置的
shlex
模块实现,例如:

import shlex
s = shlex.split('cmd -a -b -c "file with spaces.mp4" -e -f', posix=False)
print(s)

传递到
split
中的
posix=False
的目的是保留多字文件名周围的引号,因为您所需的输出格式是这样的。如果您不想保留引号,可以删除
posix
参数。

这实际上是一个很好的答案,我不知道为什么有人反对投票它,这比其他答案有一个优势,我仍然得到文件名和空格,包括引号
['cmd'、'-a'、'-b'、'-c'、'-file with spaces.mp4'、'-e'、'-f']
,谢谢你
posix=False
这正是我想要的,漂亮:)
import shlex

data=('cmd -a -b -c "file with spaces.mp4" -e -f')

new=shlex.split(data)

print(new)
['cmd', '-a', '-b', '-c', 'file with spaces.mp4', '-e', '-f']
import shlex
s = shlex.split('cmd -a -b -c "file with spaces.mp4" -e -f', posix=False)
print(s)