删除以特定字符开头的重复行

2024-04-25 00:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

如果重复行以某种方式开始,如何删除它们?你知道吗

输入示例:

%start _CreditsInfo
-(half) userCoins {
return 1;
}
%start _CreditsInfo
-(half) userLives {
return 1;
}

请求的输出:

%start _CreditsInfo
-(half) userCoins {
return 1;
}
-(half) userLives {
return 1;
}

如您所见,正常的重复删除将不起作用,我不想删除那些以%start开头的重复,例如return x;。你知道吗


Tags: 示例return方式starthalfcreditsinfousercoinsuserlives
1条回答
网友
1楼 · 发布于 2024-04-25 00:08:49

将每一行的开头(前缀)变成一个正则表达式,并保留一组您已经看到的。你知道吗

import re

class DuplicateFinder(object):

    def __init__(self, *prefixes):
        self.regexs = [re.compile('^{0}'.format(p)) for p in prefixes]
        self.duplicates = set()

    def not_duplicate(self, line):
        found = reduce(lambda r, p: r or p.search(line), self.regexs, False)
        if found:
            if found.re.pattern not in self.duplicates:
                self.duplicates.add(found.re.pattern)
                return True
            else:
                return False
        return True

df = DuplicateFinder('%start', '%other_start')


lines = """%start _CreditsInfo
-(half) userCoins {
return 1;
}
%start _CreditsInfo
-(half) userLives {
return 1;
}""".splitlines()

result = filter(df.not_duplicate, lines)

print '\n'.join(result)

产生:

%start _CreditsInfo
-(half) userCoins {
return 1;
}
-(half) userLives {
return 1;
}

相关问题 更多 >