2015-11-09 41 views

回答

2

你可以使用Python的groupby功能這個如下:

from itertools import groupby 

text = """x a 
x b 
x c 
a b 
x d 
a b 
x 123 
x 234 
x 345 
a b 
x a 
x b""" 

for k, g in groupby(text.split('\n'), lambda x: x.startswith('x')): 
    lines = list(g) 
    if k and len(lines) >= 2: 
     lines = ['y' + line[1:] for line in lines] 
    print '\n'.join(lines) 

這將顯示以下內容:

y a 
y b 
y c 
a b 
x d 
a b 
y 123 
y 234 
y 345 
a b 
y a 
y b 

使用Python 2.7.9

0

使用re.findallre.sub測試:

def replace(text): 
    regex = re.compile(r'(?m)^x') 
    if len(regex.findall(text)) > 1: 
     return regex.sub('y', text) 
    return text 

text = '''foobar 
x a 
c 
xa b 
e 
xx c 
a b 
x d 
a b 
x 123 
e 
x 234 
x 345 
ax b 
x a 
x b 
x a 
e 
''' 

 

print replace(text) 

輸出:

foobar 
y a 
c 
ya b 
e 
yx c 
a b 
y d 
a b 
y 123 
e 
y 234 
y 345 
ax b 
y a 
y b 
y a 
e 

>>> print replace('x') 
x 
>>> print replace('xa') 
xa 
>>> print replace('xaxcxc') 
xaxcxc 
>>> print replace('xa\nxcxc') 
ya 
ycxc 
>>> print replace('axa\nxc\nxc') 
axa 
yc 
yc 
>>> print replace('xa\nxc\nxc') 
ya 
yc 
yc 
相關問題