【问题标题】:What is the best way to split a string containing lists of numbers, roman numbers, and bullets?拆分包含数字、罗马数字和项目符号列表的字符串的最佳方法是什么?
【发布时间】:2018-09-28 14:16:38
【问题描述】:

我试图用不同的格式分解一个包含多个列表的字符串。最好的方法是什么?

string = "something here: 1) A i) great ii) awesome 2) B"

another_string = "But sometimes it is different (1) yep (2) not the same i. or this ii. another bullet (3.1) getting difficult huh? 3.1.1 okay i'm done"

理想情况下,我希望能够拆分任何可能的编号或项目符号列表。

字符串的期望输出:

something here: 1) A 
i) great 
ii) awesome 
2) B

另一个字符串的期望输出:

But sometimes it is different (1) yep
(2) not the same
i. or this 
ii. another bullet
(3.1) getting difficult huh?
3.1.1 okay i'm done

【问题讨论】:

  • 你想要的输出是什么?
  • @Ajax1234 刚刚修改了我的问题
  • 好吧,理论上你可以用正则表达式对数字进行分割......但是为了使代码更通用,我们将如何处理文本可能包含数字的事实?例如:(3.1) 2.4 米
  • @AntonvBR 我想 2.4 也会作为字符串的另一个子字符串被截断。不确定是否有其他解决方法。
  • @echan00 是的,但是......这里的问题是。你想做什么?您想在输出之前验证拆分吗?可能会构建一个拆分或追加的程序。

标签: python regex split


【解决方案1】:

您可以将re.split 与以下正则表达式(使用从paxdiablo 借用的罗马数字正则表达式)一起使用来拆分输入字符串,然后使用迭代器将它们连接起来:

import re
def split(s):
    i = iter(re.split(r'(\(?\d+(?:\.\d+)+\)?|\(?\d+\)|\(?\b(?=M|(?:CM|CD|D?C)|(?:XC|XL|L?X)|(?:IX|IV|V?I))M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})[.)])', s, flags=re.IGNORECASE))
    return next(i) + '\n'.join(map(''.join, zip(i, i)))

这样使用您的示例输入:

split(string)

会返回:

something here: 1) A 
i) great 
ii) awesome 
2) B

和:

split(another_string)

会返回:

But sometimes it is different (1) yep 
(2) not the same 
i. or this 
ii. another bullet 
(3.1) getting difficult huh? 
3.1.1 okay i'm done

【讨论】:

  • 嗯,那里有大正则表达式,(让我头晕目眩),:-),至少它仍然有效:-)
  • 这很棒,但我注意到其他一些问题.. 表示为 (a)、(b)、(c)、(A)、(B)、(C) 的列表是被切断。像 Mr. 和 Mrs. 这样的缩写也被取消了。 www.google.com、www.sfc.com.hk 等网址也被剪掉了。
  • @echan00 我明白了。我已经通过修复更新了我的答案。请再试一次。
  • 我看到了一个奇怪的情况,即 (i) 没有被拆分,而 (ii) 被拆分为 '(' 和 'ii)'。我还看到一个案例,其中“(Cap.”和“615)”被拆分但没有“(Cap. 486)”。知道为什么吗?
  • @blhsing 无论如何你都很棒,将答案标记为已解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2013-01-24
相关资源
最近更新 更多