我正在尝试将字符串分成单词,删除空格和标点符号。
我尝试使用 split()
方法,一次传递所有标点符号,但我的结果不正确:
>>> test='hello,how are you?I am fine,thank you. And you?'
>>> test.split(' ,.?')
['hello,how are you?I am fine,thank you. And you?']
我实际上已经知道如何使用正则表达式执行此操作,但我想弄清楚如何使用 split()
来执行此操作。请不要给我正则表达式解决方案。
最佳答案
如果您想根据 多个 分隔符拆分字符串,如您的示例所示,尽管您提出异议,您仍需要使用 re
模块,像这样:
>>> re.split('[?.,]', test)
['hello', 'how are you', 'I am fine', 'thank you', ' And you', '']
可能使用split
得到类似的结果,但是你需要为每个字符调用一次split,并且你需要迭代之前split的结果.这有效,但它是 u-g-l-y:
>>> sum([z.split()
... for z in sum([y.split('?')
... for y in sum([x.split('.')
... for x in test.split(',')],[])], [])], [])
['hello', 'how', 'are', 'you', 'I', 'am', 'fine', 'thank', 'you', 'And', 'you']
这使用 sum()
来展平上一次迭代返回的列表。
关于python - 使用 split() 在各种标点符号处划分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9797357/