python - python中字符串的上下文相关拆分

标签 python regex string

抱歉,如果这是多余的,但对内管的相当深入的搜索没有发现任何相关内容。

我有一个来自(化学)数据库的字符串,其中分隔符(逗号)偶尔出现在我希望拆分的项目中。一个示例字符串是

s = '2-Methyl-3-phythyl-1,4-naphthochinon,Vitamin, K1,Antihemorrhagic vitamin'

在这种情况下正确的分割会产生

splitS = ['2-Methyl-3-phythyl-1,4-naphthochinon', 'Vitamin, K1', 'Antihemorrhagic vitamin']

我相信,我可以设计的最准确的方法是在逗号旁边没有空格并且进一步没有被 2 个数字包围的逗号上拆分。这将留下诸如“1,4”和“维生素 K1”之类的实例,但会将字符串拆分为正确的 3 个化学名称。

我试过使用 RE 失败。我可以发布一些我尝试过的东西,但它几乎没用。非常感谢您的帮助。

编辑:最初应该包含这个。通过我的一些黑客攻击,以及来自@Borealid 的更优雅的解决方案,我已经正确地确定了拆分的位置,但是得到了可怕的输出,例如

>>> s = '2-Methyl-3-phythyl-1,4-naphthochinon,Vitamin, K1,Antihemorrhagic vitamin'
>>> pat = re.compile("([^\d\s],[^\d\s])|([^\s],[^\d\s])|([^\d\s],[^\s])")
>>> re.split(pat, s)
['2-Methyl-3-phythyl-1,4-naphthochino', 'n,V', None, None, 'itamin, K', None, '1,A', None, 'ntihemorrhagic vitamin']

似乎应该有一种方法可以首先识别要拆分的正确逗号,然后拆分逗号,从而避免名称被损坏。

再次感谢

最佳答案

您可以通过使用 lookaround 获得此行为这样你就只匹配符合你解释的逗号:

(?<!\d),(?! )|(?<=\d),(?![\d ])

它似乎对您的示例字符串有正确的行为:

>>> re.split(r'(?<!\d),(?! )|(?<=\d),(?![\d ])', s)
['2-Methyl-3-phythyl-1,4-naphthochinon', 'Vitamin, K1', 'Antihemorrhagic vitamin']

解释如下:

 (?<!\d),   # match a comma that is not preceeded by a digit...
 (?! )      # ... as long as it is not followed by a space
|           # OR
 (?<=\d),   # match a comma that is preceeded by a digit...
 (?![\d ])  # ... as long as it is not followed by a digit or a space

写完解释后我意识到 (?<=\d)正则表达式的一部分是不必要的,因为正则表达式的第一部分不匹配暗示它,这意味着您可以将其缩短为以下内容并获得相同的行为:

(?<!\d),(?! )|,(?![\d ])

关于python - python中字符串的上下文相关拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9027371/

相关文章:

python - AWS Lambda(Python): Pass list of file paths and execute each file as a separate lambda

python - 在 KeyboardInterrupt 之后杀死 subprocess.call

python - 如何遍历列表并检索最小值的索引但忽略输出列表中的重复项?

python - 用于从 < 和 > 内部提取文本字符串的正则表达式 (Python) - 例如<stringone><string-two> 等

javascript - 正则表达式 : replace everything but not a specific word

mysql - 替换 MySQL 列中的某些文本

python - 如何对 Python 程序输出的所有文本进行编码?

java - 如何使用递归压缩字符串? (RLE算法)

python - 从 Python 中的 unicode 字符串中删除 HTML 标签

string - 在SQLite3中是否有类似MySQL的POSITION()方法的字符串运算符?