从tex中删除Regex数

2024-05-13 23:57:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试清理文本,以便在机器学习应用程序中使用。基本上,这些都是“半结构化”的规范文档,我正在尝试删除干扰NLTKsent_tokenize()函数的节号。你知道吗

以下是我正在处理的文本示例:

and a Contract for the work and/or material is entered into with some other person for a
greater amount, the undersigned hereby agrees to forfeit all right and title to the
aforementioned deposit, and the same is forfeited to the Crown.
2.3.3

...

(b)

until thirty-five days after the time fixed for receiving this tender,

whichever first occurs.
2.4

AGREEMENT

Should this tender be accepted, the undersigned agrees to enter into written agreement with
the Minister of Transportation of the Province of Alberta for the faithful performance of the
works covered by this tender, in accordance with the said plans and specifications and
complete the said work on or before October 15, 2019.

我试图删除所有的分节符(例如2.3.3,2.4,(b)),但不是日期数字。你知道吗

这是我到目前为止的正则表达式:[0-9]*\.[0-9]|[0-9]\.

不幸的是,它与最后一段(2019年)中的部分日期相匹配。变成201),我真的不知道如何解决这个问题,因为我不是regex的专家。你知道吗

谢谢你的帮助!你知道吗


Tags: orandoftheto文本foris
3条回答

根据你的具体情况,我认为\n[\d+\.]+|\n\(\w\)应该有效。\n有助于区分节。你知道吗

您尝试的模式[0-9]*\.[0-9]|[0-9]\.未锚定,将匹配0+个数字、点和单个数字或|单个数字和点

它不考虑括号之间的匹配。你知道吗

假设分节符位于字符串的开头,前面可能有空格或制表符,可以使用alternation将模式更新为:

^[\t ]*(?:\d+(?:\.\d+)+|\([a-z]+\))
  • ^字符串开头
  • [\t ]*匹配0+次空格或制表符
  • (?:非捕获组
    • \d+(?:\.\d+)+匹配1+个数字并重复1+次一个点和1+个数字以匹配至少一个点2.3.32.4
    • |
    • \([a-z]+\)在括号之间匹配1+次a-z
  • )关闭非捕获组

Regex demo| Python demo

例如使用关于多行当s是您的字符串时:

pattern = r"^(?:\d+(?:\.\d+)+|\([a-z]+\))"
result = re.sub(pattern, "", s, 0, re.MULTILINE)

您可以尝试用空字符串替换以下模式

((?<=^)|(?<=\n))(?:\d+(?:\.\d+)*|\([a-z]+\))

output = re.sub(r'((?<=^)|(?<=\n))(?:\d+(?:\.\d+)*|\([a-z]+\))', '', input)
print(output)

此模式通过匹配\d+(?:\.\d+)*这样的节号来工作,但仅当它显示为行的开始时。它还将字母节头匹配为\([a-z]+\)。你知道吗

相关问题 更多 >