Skip to main content
 首页 » 编程设计

Python被多个分隔符分割,包括空格

2025年05月04日15mq0036

输入:

Some Text here: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc. 

代码:

import re 
 
input_words = list(re.split('\s+', input())) 
print(input_words) 

完美运行并返回我:

['Some', 'Text', 'here:', 'Java,', 'PHP,', 'JS,', 'HTML', '5,', 'CSS,', 'Web,', 'C#,', 'SQL,', 'databases,', 'AJAX,', 'etc.'] 

但是当添加一些其他分隔符时,像这样:

import re 
 
input_words = list(re.split('\s+ , ; : . ! ( ) " \' \ / [ ] ', input())) 
print(input_words) 

它不再被空格分割了,我哪里错了?

预期输出为:

['Some', 'Text', 'here', 'Java', 'PHP', 'JS', 'HTML', '5', 'CSS', 'Web', 'C#', 'SQL', 'databases', 'AJAX', 'etc'] 

请您参考如下方法:

您应该根据包含所有这些符号的正则表达式 alternation 进行拆分:

input_words = re.split('[\s,;:.!()"\'\\\[\]]', input()) 
print(input_words) 

这是对您问题的字面回答。您可能想要使用的实际解决方案是在两端使用可选空格的符号进行拆分,例如

input = "A B ; C.D   ! E[F] G" 
input_words = re.split('\s*[,;:.!()"\'\\\[\]]?\s*', input) 
print(input_words) 

打印:

['A', 'B', 'C', 'D', 'E', 'F', 'G']