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してアイテムを1つの文字列にまとめます。

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(*...)ます: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 に答える