如何在python中编写正则表达式?我想写R.E.对于以下示例

时间:2012-10-09 16:28:12

标签: python regex string

如果输入字符串如下:

"that`s not good thing ! you havn`t understand anything ?"

我想将其转换为:

" thats not good thing you havnt understand anything "

这就是我想要的吗?

我尝试以下reg.exp。

line = "that`s not good thing ! you havn`t understand anything ?"
text=re.sub("[^\w]"," ",line).split()

但它无法用于所需的输出。请提出相同的建议。

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找这个:

text = re.sub("[^\\w\\s]", "", line)

请注意,除了常规字符外,您似乎还想要保留空格。

然后,如果您真的在该行中的单词之后,可以执行text.split()

演示:

In [29]: line = "that`s not good thing ! you havn`t understand anything ?"

In [30]: text=re.sub("[^\\w\\s]","",line)

In [31]: text
Out[31]: 'thats not good thing  you havnt understand anything '

In [32]: text.split()
Out[32]: ['thats', 'not', 'good', 'thing', 'you', 'havnt', 'understand', 'anything']