Last active
March 29, 2021 19:02
-
-
Save trinker/e504e067f01d35e8f469569621c9e65e to your computer and use it in GitHub Desktop.
textread fgsub equivalent in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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