【问题标题】:How to split a multi word string but escaping split at certain word combinations?如何拆分多字串但在某些单词组合处转义拆分?
【发布时间】:2019-10-16 15:44:58
【问题描述】:

假设我有一个字符串:

mystr = "my name is some good name"

# I want to split at white space except for the part "name is"
expectedoutput = ["my", "name is", "some", "good", "name"]

无论有没有 shlex,我如何做到这一点?

我尝试做的方式是:

Import shlex
def careful_split(inputstr, donot_split = "name is"):
    strlex = shlex.shlex(inputstr, commenters =?, posit = ?)
    strlex.wordchars = ?
    #and other shlex function

    return list(strlex)

【问题讨论】:

  • 跳过name is部分背后的逻辑是什么?
  • 没有任何逻辑,只是我为函数提供了不应该拆分的单词组合列表。例如:def careful_split(inputstr, donot_split = "name is"):

标签: python-3.x string split shlex


【解决方案1】:

您可以使用带有negative lookahead 的正则表达式。

import re

re.split(r'(?!name)\s+(?!is)', mystr)

有更多案例的示例:

>>> mystr = "my name is some good name is hi name"
>>> re.split(r'(?!name)\s+(?!is)', mystr)
['my', 'name is', 'some', 'good', 'name is', 'hi', 'name']

请注意,这不会拆分任何*.name is.* 短语。所以“name is not”也不会被拆分。我不确定在这些情况下您想要的行为是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2012-05-13
    • 1970-01-01
    • 2019-11-01
    • 2017-11-02
    相关资源
    最近更新 更多