Skip to main content
 首页 » 编程设计

python之在带有单词 "said"的句子周围添加引号

2024年11月01日12unruledboy

好的正则表达式大师,我有一个很长的文本,我试图在包含单词“he said”和类似变体的句子中添加引号。

例如:

s = 'This should have no quotes. This one should he said. But this one should not. Neither should this. But this one should she said.' 

应该导致:

This should have no quotes. "This one should," he said. But this one should not. Neither should this. "But this one should," she said. 

到目前为止,我可以很接近,但不太正确:

>>> import re 
>>> m = re.sub(r'\.\W(.*?) (he|she|it) said.', r'. "\1," \2 said.', s) 

结果:

>>> print m 
This should have no quotes. "This one should," he said. But this one should not. "Neither should this. But this one should," she said. 

如您所见,它在第一个实例周围正确地放置了引号,但对第二个实例放置得太早了。任何帮助表示赞赏!

请您参考如下方法:

评论中指出了一些不同的有效情况,但为了解决您面临的问题:

它引用了整个句子,因为它看到 one should not. 末尾的句点.您真正想要的是只引用最后 时期。因此,在匹配的括号中确保不要包含句点,如下所示:

m = re.sub(r'\.\W([^\.]*?) (he|she|it) said.', r'. "\1," \2 said.', s) 

对于像 "Dr. Seuss likes to eat, she said" 这样的句子中带有句点的东西,这将失败但这是另一个问题。