我想将文本拆分为列表,其中带空格的文件名应视为一个项目:示例
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循环,但是很讨厌,是否有使用正则表达式或其他看起来不太丑的方法?
实际上,在这种情况下,我将不使用正则表达式。这是shlex.split()
的用途:
shlex.split()
打印:
import shlex
s = shlex.split( 'cmd -a -b -c "file with spaces.mp4" -e -f' )
print(s)
尝试['cmd', '-a', '-b', '-c', 'file with spaces.mp4', '-e', '-f']
shlex
收益率,
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']
模块来完成,例如:
shlex
import shlex
s = shlex.split('cmd -a -b -c "file with spaces.mp4" -e -f', posix=False)
print(s)
传递给posix=False
的目的是保留多字文件名周围的引号,因为所需的输出格式是这样的。如果您不想保留引号,则可以删除split
参数。
使用正则表达式匹配:
posix
最终后跟另一个"
("
),或"[^"]*"
):\S+