【问题标题】:Split string by commas except when in bracket用逗号分割字符串,除非在括号中
【发布时间】:2020-04-26 20:43:04
【问题描述】:

我想用逗号分割字符串,除非在括号中,但我的问题是当我有括号时

这是一个例子:

b='hi, this(me,(you)) , hello(a,b)'
re.split(r',(?![^\(]*[\)])', b)
['hi', ' this(me', '(you)) ', ' hello(a,b)']

我的期望是:

['hi', ' this(me,(you))',' hello(a,b)']

我看到了与我想要的类似的问题,但它不像我期望的那样工作我不知道为什么

1-Split string at commas except when in bracket environment

2-Python - Split by comma skipping the content inside parentheses

有什么帮助吗?

【问题讨论】:

  • 您发布的 1 个链接会有您的答案,但如果您注意到,它们的括号是 {,而您的是 (。您可以修改那里给出的答案以使其适合您吗?花一些时间阅读答案中提供的代码。
  • 是的,我已经修改了它,但仍然无法工作@paritosh

标签: python regex string


【解决方案1】:

尝试使用模式(?!\S\)|\()

例如:

import re

b = ['hi, this(me,(you)) , hello(a,b)', 'hi, this(me,(you))']
for i in b:
    print(re.split(r',(?!\S\)|\()', i))

输出:

['hi', ' this(me,(you)) ', ' hello(a,b)']
['hi', ' this(me,(you))']

【讨论】:

  • 如果我有两个以上的括号怎么办?比如:hi(a,(b, c(d,e)))
  • 我怎样才能让它跳过里面的任何逗号并取最后一个“)”
【解决方案2】:

没有正则表达式的方法可能是这样的:

b='hi, this(me,(you))'

phrase = ''
phrases = []

in_parenth = 0

for l in b:

    if l == '(':
        in_parenth += 1
    elif l == ')':
        in_parenth -= 1

    if l == ',' and in_parenth == 0:
        if phrase.strip():
            phrases.append(phrase)
        phrase = ''
    else:
        phrase += l

if phrase.strip():
    phrases.append(phrase)

print(phrases)

【讨论】:

  • 但它不会分割单词,我想用逗号分割,因为我会计算单词的数量并且它有(意味着单词连接
  • 你写道你想用逗号分割一个字符串而不是分割单词,在你的例子中每个单词都用逗号分隔。如果你愿意,把它说得更清楚会很有帮助。
【解决方案3】:

如果主要文本组都用逗号和空格分隔,则可以使用re.split

import re
b='hi, this(me,(you)) , hello(a,b)'
result = re.split(',\s', b)

输出:

['hi', 'this(me,(you)) ', 'hello(a,b)']

不过,你也可以使用递归来解析字符串:

def parse(d):
  if (v:=next(d, None)) is not None and v != ')':
     yield v if v != '(' else f'({"".join(parse(d))})'
     yield from parse(d)

r, c, l = list(filter(lambda x:x != ',', parse(iter(re.findall('\w+|\(|\)|,', b))))), '', []
for i in r:
   if not i.endswith(')'):
      l.append(c)
      c = i
   else:
      l.append(c+i)
      c = ''

l.append(c)
final_result = list(filter(None, l))

输出:

['hi', 'this(me,(you))', 'hello(a,b)']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 2017-04-07
    • 2010-12-11
    • 2015-01-04
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多