python - 使用 split() 在各种标点符号处划分字符串

标签 python string split

我正在尝试将字符串分成单词,删除空格和标点符号。

我尝试使用 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/

相关文章:

python - 如何使 Python 字符串版本不可知

xcode - xcode将NSString拆分为其他NSString

python - 在数组中搜索关键字-python

python - 给定另一个 numpy 数组,将 numpy.ndarray 的一些元素替换为零

python - 将具有各种数字数据类型的结构化数组转换为常规数组

python - Paramiko 未正确返回 grep

python - 如何在不破坏 DataFrame.append() 的情况下子类化或以其他方式扩展 pandas DataFrame?

java - 如果子字符串不在我的原始字符串中,如何避免 StringIndexOutOfBoundsException?

python - 如何从 python 中的拆分块中删除静默 block ?

r - 如何编写在数值中包含前导零的 substr 版本(在 R 中)?