Skip to content

Instantly share code, notes, and snippets.

@mossbanay
Last active January 14, 2016 11:01
Show Gist options
  • Save mossbanay/b1c33f5bab29a5755823 to your computer and use it in GitHub Desktop.
Save mossbanay/b1c33f5bab29a5755823 to your computer and use it in GitHub Desktop.
Random spambot
import re
import random
def random_keyword(match):
keywords = match.group(1).split('|')
return random.choice(keywords)
r = re.compile(r'{([^}]+)}')
with open('comment.txt') as f:
text = f.read()
output = re.sub(r, random_keyword, text)
print(output)
@jamesrcurran
Copy link

Since you've used parentheses within the regex you can just go match_obj.group(1) rather than do additional slicing. I also wouldn't suffix an object variable with _obj – it is pretty redundant. Otherwise, nice!

@mossbanay
Copy link
Author

I just noticed before I wasn't actually using my capture group yup

@mossbanay
Copy link
Author

Bonus extra readable version:

import re,random
with open('comment.txt')as f:print(re.sub(r'{([^}]+)}',lambda x:random.choice(x.group(1).split('|')),f.read()))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment