繁体   English   中英

从字符串中删除多个字符序列

[英]Remove multiples of character sequence from string

如果我有这样的字符串:

my_string = 'this is is is is a string'

我将如何删除倍数is s以便仅显示一个?

此字符串可以包含任意数量的is在诸如有

my_string = 'this is is a string'
other_string = 'this is is is is is is is is a string'

我想可以使用正则表达式解决方案,但是我不确定该怎么做。 谢谢。

您可以使用itertools.groupby

from itertools import groupby
a = 'this is is is is a a a string string a a a'
print ' '.join(word for word, _ in groupby(a.split(' ')))

这是我的方法:

my_string = 'this is is a string'
other_string = 'this is is is is is is is is a string'
def getStr(s):
    res = []
    [res.append(i) for i in s.split() if i not in res]
    return ' '.join(res)

print getStr(my_string)
print getStr(other_string)

输出:

this is a string
this is a string

更新正则表达式的攻击方式:

import re
print ' '.join(re.findall(r'(?:^|)(\w+)(?:\s+\1)*', other_string))

现场演示

如果您想一次删除所有重复项,可以尝试

l = my_string.split()
tmp = [l[0]]
for word in l:
    if word != tmp[-1]:
        tmp.append(word)
s = ''
for word in tmp:
    s += word + ' '
my_string = s

当然,如果您要比这更智能,它将变得更加复杂。

对于单行:

>>> import itertools
>>> my_string = 'this is is a string'
>>> " ".join([k for k, g in itertools.groupby(my_string.split())])
'this is a string'

正则表达式可以解救!

((\b\w+\b)\s*\2\s*)+
# capturing group
# inner capturing group
# ... consisting of a word boundary, at least ONE word character and another boundary
# followed by whitespaces
# and the formerly captured group (aka the inner group)
# the whole pattern needs to be present at least once, but can be there
# multiple times

Python代码

import re

string = """
this is is is is is is is is a string
and here is another another another another example
"""
rx = r'((\b\w+\b)\s*\2\s*)+'

string = re.sub(rx, r'\2 ', string)
print string
# this is a string
# and here is another example

演示

在regex101.comideone.com 查看有关此方法的演示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM