Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def removeTemplateArguments(str, depthToRemove):
- """ Remove template arguments deeper than depthToRemove
- so removeTemplateArguments("foo<int>()", 1) gives foo<>()
- removeTemplateArguments("foo< bar<int> >()", 1) gives foo< >()
- removeTemplateArguments("foo< bar<int> >()", 2) gives foo< bar<> >()"""
- if depthToRemove <= 0:
- return str
- currDepth = 0
- res = ""
- for c in str:
- if currDepth < depthToRemove:
- res += c
- if c == "<":
- currDepth += 1
- elif c == ">":
- currDepth -= 1
- if currDepth < depthToRemove:
- res += ">"
- return res
- from itertools import groupby
- def remove_arguments(template, depth):
- res = []
- curr_depth = 0
- for k,g in groupby(template, lambda x: x in ['<', '>']):
- text = ''.join(g) # rebuild the group as a string
- if text == '<':
- curr_depth += 1
- # it's important to put this part in the middle
- if curr_depth < depth:
- res.append(text)
- elif k and curr_depth == depth: # add the inner <>
- res.append(text)
- if text == '>':
- curr_depth -= 1
- return ''.join(res) # rebuild the complete string
- >>> remove_arguments('foo<int>()', 1)
- foo<>()
- >>> remove_arguments('foo< bar<int> >()', 1)
- foo<>()
- >>> remove_arguments('foo< bar<int> >()', 2)
- foo< bar<> >()
- >>> remove_arguments('foo< bar >()', 2)
- foo< bar >()
- groupby(template, lambda x: x in ['<', '>']) # most obvious one
- groupby(template, lambda x: x in '<>') # equivalent to the one above
- groupby(template, '<>'.__contains__) # this is ugly ugly
- groupby(template, '<>'.count) # not obvious, but looks sweet
- def get_level(ch, level=[0]):
- current = level[0]
- if ch == '<':
- level[0] += 1
- if ch == '>':
- level[0] -= 1
- current = level[0]
- return current
- def remove_arguments(template, depth):
- res = []
- for k,g in groupby(template, get_level):
- if k < depth:
- res.append(''.join(g))
- return ''.join(res)
- import re
- def removeTemplateArguments(function_name, depth):
- to_match = "(?P<class>w+)<s*(?P<nested>.*)s*>(?P<paren>(?)?)"
- parts = re.match(to_match, function_name).groupdict()
- nested = '' if depthToRemove == 1
- else removeTemplateArguments(parts['nested'], depth-1)
- return "%s<%s>%s" % (parts['class'], nested, parts['paren'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement