亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從字符串中創建兩個列表,這些字符串在方括號之間包含和不包括

從字符串中創建兩個列表,這些字符串在方括號之間包含和不包括

皈依舞 2021-05-30 10:58:13
支持我們有一個像這樣的字符串:s = u'apple banana lemmon (hahaha) dog cat whale (hehehe) red blue black'我要創建以下列表:including = ['hahaha', 'hehehe'] excluding = ['apple banana lemmon (', ') dog cat whale (', ') red blue black']第一個列表是直接使用正則表達式:including = re.findall('\((.*?)\)',s)但是我無法為其他列表獲得類似的信息。你可以幫幫我嗎?先感謝您!!
查看完整描述

3 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

excluding = re.split('|'.join(including), s)

對于您知道包含信息將不包含特殊字符或正則表達式定義的簡單情況。

如果您不確定是否會出現這種情況:

re.split('|'.join(map(re.escape, including)), s)

這將轉義特殊的正則表達式字符,否則將導致re.split函數功能異常


查看完整回答
反對 回復 2021-06-01
?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

使用正則表達式

a = re.findall('\)?[^()]*\(?', s)

excluded = a[::2]

included = a[1::2]

print(included, excluded, sep='\n')


['hahaha', 'hehehe', '']

['apple banana lemmon (', ') dog cat whale (', ') red blue black']

照顧空字符串

a = re.findall('\)?[^()]*\(?', s)

excluded = [*filter(bool, a[::2])]

included = [*filter(bool, a[1::2])]

print(included, excluded, sep='\n')


['hahaha', 'hehehe']

['apple banana lemmon (', ') dog cat whale (', ') red blue black']

沒有正則表達式

from itertools import cycle


def f(s):

  c = cycle('()')

  a = {'(': 1, ')': 0}

  while s:

    d = next(c)

    i = s.find(d)

    if i > -1:

      j = a[d]

      yield d, s[:i + j]

      s = s[i + j:]

    else:

      yield d, s

      break


included = []

excluded = []


for k, v in f(s):

  if k == '(':

    excluded.append(v)

  else:

    included.append(v)


print(included, excluded, sep='\n')


['hahaha', 'hehehe']

['apple banana lemmon (', ') dog cat whale (', ') red blue black']

相同想法但不覆蓋 s

from itertools import cycle


def f(s):

  c = cycle('()')

  a = {'(': 1, ')': 0}

  j = 0

  while True:

    d = next(c)

    i = s.find(d, j)

    if i > -1:

      k = a[d]

      yield d, s[j:i + k]

      j = i + k

    else:

      yield d, s[j:]

      break


included = []

excluded = []


for k, v in f(s):

  if k == '(':

    excluded.append(v)

  else:

    included.append(v)


print(included, excluded, sep='\n')


['hahaha', 'hehehe']

['apple banana lemmon (', ') dog cat whale (', ') red blue black']


查看完整回答
反對 回復 2021-06-01
?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

您可以使用正向后視和正向前瞻來拆分括號之間的單詞:


>>> re.split(r'(?<=\().*?(?=\))', s)

['apple banana lemmon (', ') dog cat whale (', ') red blue black']


查看完整回答
反對 回復 2021-06-01
  • 3 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號