Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在句子周围加上引号,用“quot;说";_Python_Regex_Text - Fatal编程技术网

Python 在句子周围加上引号,用“quot;说";

Python 在句子周围加上引号,用“quot;说";,python,regex,text,Python,Regex,Text,好的,正则表达式大师,我有一个很长的文本,我试图在包含“他说”和类似变体的句子中添加引号 例如: 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

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

例如:

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.

如您所见,它在第一个实例周围正确地放置了quote,但在第二个实例中放置它太早了。感谢您的帮助

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

它引用了整个句子,因为它在
结尾处看到了句号,而不应该这样做。
。你真正想要的,是只引用上一段。因此,在匹配的括号中,确保不包括句点,如:

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

如果句子中有句号,这将失败,如“苏斯博士喜欢吃东西,”她说“,但这是另一个问题。

这似乎更像是自然语言处理问题,而不是简单的正则表达式问题。除非你引用的句子总是以预定义的格式。不要太在意捕捉代词的所有实例等。我(目前)的问题是在正确的位置获得引用。你会如何处理像
“他说这很难。”
?这里不需要引号,因为它不是直接的引号。我希望修改我的工作正则表达式,以便在单独的过程中获得这些实例。任何人都可以在一个正则表达式中同时获得加分,但我认为这可能是不可能的……在4分钟内允许批准标记,这非常有效!
^
是回顾一个句点和空格的东西吗?@JeffThompson-不。
[^\.]
是说“任何不是句点的字符”。@JeffThompson是的,就像iCodez说的。很高兴它起作用了!在工作中有一个很快的休息,没有什么比在休息时看regex更好的了。。。