使用regex拆分项目列表

2024-05-19 11:03:49 发布

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

首先,我有一个由项目列表组成的字符串,这些项目可以由一个枚举器(逗号/‘and’)或一个文章(‘a’/‘an’/‘the’)拼接。请注意,如果有枚举器,则可以省略冠词,反之亦然

例如,让我们看看这个输入:

a paper, leaf the clock and an angel

这必须分为:

  • a paper
  • leaf
  • the clock
  • an angel

第一个示例只有单个名称的项,因此让我们看另一个示例:

a paper with some letters, a torn leaf and clock and an angel doll

这必须分为:

  • a paper with some letters
  • torn leaf
  • clock
  • an angel doll

我已经为此尝试了一些正则表达式,最接近的是:

(?:\b(?P<article>the|an|a)\b)\s(?P<object>\b.+?\b(?=\b(?:the|an|a|$)\b))

当然,我没有考虑','/'和'分裂,因为我不明白,很遗憾。你知道吗

最后,如您所见,我使用组来识别/分离对象文章。如果可以的话那就太好了。你有什么建议。。。你知道吗


Tags: andthe项目an示例with文章some
3条回答

就用re.split()

import re

a = "a paper with some letters, a torn leaf and clock and an angel doll"

### put every separator you want to remove after a |
re.split(', |and |a ',a)
# result:
['', 'paper with some letters', '', 'torn leaf ', 'clock ', '', 'angel doll']

如果需要保留分隔符,请使用括号:

[i for i in re.split('(, |and |a )',a) if i]
# result:
['a ', 'paper with some letters', ', ', 'a ', 'torn leaf ', 'and ', 'clock ', 'and ', 'an angel doll']

按照与re.split()匹配的正则表达式的降序,枚举所有较小的事例:

import re

s = "a paper with some letters, a torn leaf and clock and an angel doll"

re.split(r'^an |^a |^the |, and a |, and an |, and the |, and |, and an |, an |, the |, a | and an | and | an | the', s)
# ['', 'paper with some letters', 'torn leaf', 'clock', 'angel doll']

剩下的只是清理'',以此类推。你知道吗

要保留匹配的内容,请将正则表达式用括号括起来,如文档所示:

re.split(r'(^an |^a |^the |, and a |, and an |, and the |, and |, and an |, an |, the |, a | and an | and | an | the )', s)

# ['', 'a ', 'paper with some letters', ', a ', 'torn leaf', ' and ', 'clock', ' and an ', 'angel doll']

关于我想解决的具体任务,我有了另一个想法, 步骤如下:

  • 如果后面有“and”或“or”,则添加默认项目(the)
"( and|,) (?!the|an|a)|^(?!the|an|a)" # replace with " the "
  • 从输入文本中删除每个'和'或',(现在每个对象都应该用冠词分开)
"( and|,) " # replace with " "
  • 将输入内容拆分为article+除article以外的所有内容
"(?P<article>the|an|a) (?P<object>.+?(?= (?:the|an|a)\b)|[^$]*)"

PS:如果有人知道最后一个正则表达式的替代方法,请随时发布!:)

相关问题 更多 >

    热门问题