Skip to content

Instantly share code, notes, and snippets.

@trinker
Last active March 29, 2021 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinker/e504e067f01d35e8f469569621c9e65e to your computer and use it in GitHub Desktop.
Save trinker/e504e067f01d35e8f469569621c9e65e to your computer and use it in GitHub Desktop.
textread fgsub equivalent in python
text = ['df dft sdf', 'sd fdggg sd dfhhh d', 'ddd']
def dbllttrwordrev(match):
match = match.group()
return '<<{}>>'.format(match[::-1])
{
'function': [re.sub("\\b\\w*([a-z])(\\1{2,})\\w*\\b", dbllttrwordrev, x, flags = re.IGNORECASE) for x in text],
'lambda': [re.sub("\\b\\w*([a-z])(\\1{2,})\\w*\\b", lambda x: '<<{}>>'.format(x.group()[::-1]) , x, flags = re.IGNORECASE) for x in text]
}
def fgsub(text, pattern, fun, ignore_case = False):
if ignore_case:
case_flag = re.IGNORECASE
else:
case_flag = 0
sub = re.sub
return [sub(pattern, fun, x, flags = case_flag) if x is not None else None for x in text]
txt = [None, 'I want 32 grapes', 'he wants 4 ice creams', 'they want 1,234,567 dollars']
import re
import math
def number_half(match):
return '{:,}'.format(math.ceil(int(re.sub('[^0-9]', '', match.group()))/2))
#return [re.sub('[^0-9]', '', x) for x in text]
fgsub(txt, '[\\d,]+', number_half)
fgsub(txt, '[\\d,]+', lambda match: '{:,}'.format(math.ceil(int(re.sub('[^0-9]', '', match.group()))/2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment