相关疑难解决方法(0)

将字符串拆分为单词和标点符号

我正在尝试将字符串拆分为单词和标点符号,将标点符号添加到拆分生成的列表中.

例如:

>>> c = "help, me"
>>> print c.split()
['help,', 'me']
Run Code Online (Sandbox Code Playgroud)

我真正希望列表看起来像是:

['help', ',', 'me']
Run Code Online (Sandbox Code Playgroud)

所以,我希望字符串在空格中分割,并且从单词中分割出标点符号.

我试图先解析字符串,然后运行拆分:

>>> for character in c:
...     if character in ".,;!?":
...             outputCharacter = " %s" % character
...     else:
...             outputCharacter = character
...     separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
Run Code Online (Sandbox Code Playgroud)

这会产生我想要的结果,但在大文件上却很慢.

有没有办法更有效地做到这一点?

python string split

57
推荐指数
5
解决办法
6万
查看次数

标签 统计

python ×1

split ×1

string ×1