【问题标题】:Split a string with one delimiter but multiple conditions使用一个分隔符但多个条件拆分字符串
【发布时间】:2015-10-28 09:57:12
【问题描述】:

早上好,

我发现多个线程处理使用多个分隔符分割字符串,但不是一个分隔符和多个条件

我想按句子分割以下字符串:

desc = Anna Pytlik 博士是保守和美学牙科方面的专家。她会说英语和波兰语。

如果我这样做:

[t.split('.') for t in desc]

我明白了:

['Dr','Anna Pytlik 是保守和美学牙科方面的专家','她会说英语和波兰语。']

我不想拆分“博士”之后的第一个点。如何添加子字符串列表,在这种情况下 .split('.') 不适用?

谢谢!

【问题讨论】:

标签: python regex python-2.7 split string-split


【解决方案1】:

您可以将re.splitnegative lookbehind 一起使用:

>>> desc = "Dr. Anna Pytlik is an expert in conservative and aesthetic dentistry. She speaks both English and Polish."
>>> re.split(r"(?<!Dr|Mr)\. ", desc)
['Dr. Anna Pytlik is an expert in conservative and aesthetic dentistry',
 'She speaks both English and Polish.']

只需添加更多“例外”,以| 分隔。


更新:似乎负后视要求所有备选方案都具有相同的长度,因此这不适用于两个“博士”。和“教授”。一种解决方法可能是用. 填充模式,例如(?&lt;!..Dr|..Mr|Prof)。您可以轻松编写一个辅助方法,根据需要用尽可能多的. 填充每个标题。但是,如果文本的第一个单词是 Dr.,这可能会中断,因为 .. 不会被匹配。

另一种解决方法可能是首先用一些占位符替换所有标题,例如"Dr." -> "{DR}""Prof." -> "{PROF}",然后拆分,然后交换原来的标题。这样你甚至不需要正则表达式。

pairs = (("Dr.", "{DR}"), ("Prof.", "{PROF}")) # and some more
def subst_titles(s, reverse=False):
    for x, y in pairs:
        s = s.replace(*(x, y) if not reverse else (y, x))
    return s

例子:

>>> text = "Dr. Anna Pytlik is an expert in conservative and aesthetic dentistry. Prof. Miller speaks both English and Polish."
>>> [subst_titles(s, True) for s in subst_titles(text).split(". ")]
['Dr. Anna Pytlik is an expert in conservative and aesthetic dentistry', 'Prof. Miller speaks both English and Polish.']

【讨论】:

  • 实际上,这仅在负后视的长度固定(此处为 2 个字符)时才有效。我还想检查“med”或“prof”之类的东西。有什么建议吗?
【解决方案2】:

你可以分开然后再加入 Dr/Mr/... 它不需要复杂的正则表达式并且可以更快(您应该对其进行基准测试以选择最佳选项)。

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多