1

假设我在一个名为“main”的列表中有一堆字符串。如何遍历“main”,如果找到匹配项,则删除“main”中匹配的部分,然后将匹配的文本添加到名为“new”的新列表中?

Python

main = ['text \fc + \fr this is my match1 \fc* text', 'text \fc + \fr this is my match2 \fc* text', 'text', 'text', 'text \fc + \fr this is my match \fc* text']
new = []

def rematch(pattern, inp):
  matcher = re.compile(pattern)
  matches = matcher.match(inp)
  if matches:
    new.append(matches)
    #remove match from "main" somehow?

for x in main:
  for m in rematch('\\fc \+ \\fr(.*?)\\fc\*', x):

结果:

main = ['text text', 'text text', 'text', 'text', 'text text']

new = ['this is my match1', 'this is my match2', 'this is my match3']
4

1 回答 1

2
In [33]: import re

In [34]: pat = re.compile('\\fc \+ \\fr(.*?)\\fc\*')

In [43]: main, new = zip(*[(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]])

In [44]: new = [n.strip() for n in new if n]

In [45]: main
Out[45]: ('text  text', 'text  text', 'text', 'text', 'text  text')

In [46]: new
Out[46]: ['this is my match1', 'this is my match2', 'this is my match']

解释:

注意使用时会发生什么pat.split

In [37]: pat.split(main[0])
Out[37]: ['text ', ' this is my match1 ', ' text']

这与您想要的类似,只是您需要 中的奇数项main和 中的偶数项new。我们稍后会谈到。

首先,让我们应用pat.split到 中的每个项目main

In [51]: [pat.split(m) for m in main]
Out[51]: 
[['text ', ' this is my match1 ', ' text'],
 ['text ', ' this is my match2 ', ' text'],
 ['text'],
 ['text'],
 ['text ', ' this is my match ', ' text']]

接下来,让我们将奇数项与偶数项分开,并使用''.join将这些项组合成一个字符串:

In [52]: [(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]]
Out[52]: 
[('text  text', ' this is my match1 '),
 ('text  text', ' this is my match2 '),
 ('text', ''),
 ('text', ''),
 ('text  text', ' this is my match ')]

从这里,我们可以使用zip(*...)to 分开:mainnew

In [53]: main, new = zip(*[(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]])

In [54]: main
Out[54]: ('text  text', 'text  text', 'text', 'text', 'text  text')

In [55]: new
Out[55]: (' this is my match1 ', ' this is my match2 ', '', '', ' this is my match ')
于 2013-02-21T15:24:31.870 回答