繁体   English   中英

如何根据多个条件正则表达式将句子拆分为多个句子?

[英]how to split the sentence into multiple sentence based on multiple condition regex?

我有以下句子。 如果句子有点或匹配的单词,我需要将句子分成多个句子。

句子 1:尝试序列化参数http://uri.org/:Message 时出错。 数据协定名称为“enumStatus:”的 InnerException 消息不是预期的。

预期结果:

senetences =    1. There was an error while trying to serialize parameter http://uri.org/:vMessage.
                2. The InnerException message with data contract name 'enumStatus:' is not expected.
                        

句子 2:ORA-01756:引用的字符串没有正确终止 ORA-06512:在 module1,第 48 行 ORA-06512:在第 1 行

预期结果:

senetences = 1. ORA-01756: quoted string not properly terminated
             2. ORA-06512: at module1, line 48
             3. ORA-06512: at line 1
                        

我使用下面的正则表达式来拆分句子。

 sentences = re.split(r'(?<=\w\.)\s|ORA-[0-9]{1,8}', input)
 

这里的问题是,对于第一种情况,如果后跟点的任何单词工作正常。 对于第二种情况,我可以拆分句子。 我有2个问题。

  1. 它正在删除整个匹配词“ORA-”。 但我需要整个词。
  2. 我得到 4 个句子而不是 3 个句子。
    1. (第一个是空的,因为它有起始词 ORA-)
    2. 带引号的字符串未正确终止
    3. 在模块 1,第 48 行
    4. 在第 1 行

在这种情况下,我需要 3 个句子。

任何帮助将非常感激。

您可以使用此正则表达式进行拆分:

\s+(?=ORA-\d+)|(?<=\.)\s+(?=[A-Z])

正则表达式演示

正则表达式详情:

  • \\s+(?=ORA-\\d+) :如果后面跟着ORA-和 1+ 数字,则匹配 1+ 个空格
  • | : 或者
  • (?<=\\.)\\s+(?=[AZ]) :匹配 1+ 个空格,如果前面是一个点,后面跟一个大写字母

代码演示

代码:

import re
arr = ["There was an error while trying to serialize parameter http://uri.org/:Message. The InnerException message with data contract name 'enumStatus:' is not expected.", "ORA-01756: quoted string not properly terminated ORA-06512: at module1, line 48 ORA-06512: at line 1"]

rx = re.compile(r'\s+(?=\bORA-\d+)|(?<=\.)\s+(?=[A-Z])')
for i in arr: print (rx.split(i))

输出:

['There was an error while trying to serialize parameter http://uri.org/:Message.', "The InnerException message with data contract name 'enumStatus:' is not expected."]
['ORA-01756: quoted string not properly terminated', 'ORA-06512: at module1, line 48', 'ORA-06512: at line 1']
(?<=\w\.)\s|(ORA-[0-9]{1,8})

你可以试试这个并替换为\\n\\1

见演示。

https://regex101.com/r/8yvUuZ/1/

# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?<=\w\.)\s|(ORA-[0-9]{1,8})"

test_str = ("ORA-01756: quoted string not properly terminated ORA-06512: at module1, line 48 ORA-06512: at line 1\n"
    "There was an error while trying to serialize parameter http://uri.org/:Message. The InnerException message with data contract name 'enumStatus:' is not expected.")

subst = "\\n\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM