Skip to main content
 首页 » 编程设计

python之正则表达式用括号前的空格替换点

2024年10月17日33wuhuacong

我正在处理一些客户评论,其中一些不符合语法规则。 For Example (Such as s and b.) 在下面的文本中,为前面的句子提供了更多的解释,用两个点包围。

   text = "I was initially scared of ANY drug after my experience. But about a year later I tried. (Such as s and b.). I had a very bad reaction to this." 

首先,我想找到。 (如s和b.).然后将(如s和b.)前的点替换为空格。这是我的代码,但它不起作用。

text = re.sub (r'(\.)(\s+?\(.+\)\s*\.)', r' \2 ', text ) 

输出应该是:

 "I was initially scared of ANY drug after my experience. But about a year later I tried  (Such as s and b.). I had a very bad reaction to this." 

我正在使用 python。

请您参考如下方法:

提供的示例没有多大意义,因为唯一的变化是 ` 字符向左移动了一个位置。

但是,这可能会奏效(将圆点保留在括号内):

text = re.sub(r'\.\s*\)\s*\.', '.)', text) 

或者这个放在外面:

text = re.sub(r'\.\s*\)\s*\.', ').', text) 

编辑:或者您正在寻找这个来替换左括号之前的点?

text = re.sub(r'\.(?=\s*\(.*?\)\.)', ').', text)