From 07d3c3df0c65d6114e235fdbdaed60b6ae071b85 Mon Sep 17 00:00:00 2001 From: Scott Date: Sun, 17 Jul 2016 21:42:28 -0500 Subject: [PATCH] Moved loremipsum import logic out of main shreddit code --- shreddit/shredder.py | 19 +------------------ shreddit/util.py | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 18 deletions(-) create mode 100644 shreddit/util.py diff --git a/shreddit/shredder.py b/shreddit/shredder.py index d4f3cb0..4408e70 100644 --- a/shreddit/shredder.py +++ b/shreddit/shredder.py @@ -6,27 +6,10 @@ import json import yaml import praw from re import sub -from random import shuffle, randint from datetime import datetime, timedelta from praw.errors import (InvalidUser, InvalidUserPass, RateLimitExceeded, HTTPException, OAuthAppRequired) from praw.objects import Comment, Submission -try: - from loremipsum import get_sentence # This only works on Python 2 -except ImportError: - def get_sentence(): - return "I have been Shreddited for privacy!" - - os_wordlist = "/usr/share/dict/words" - if os.name == "posix" and os.path.isfile(os_wordlist): - # Generate a random string of words from our system's dictionary - fh = open(os_wordlist) - words = fh.read().splitlines() - fh.close() - shuffle(words) - - def get_sentence(): - return " ".join(words[:randint(50, 150)]) -assert get_sentence +from shreddit.util import get_sentence def shred(config, praw_ini=None): diff --git a/shreddit/util.py b/shreddit/util.py new file mode 100644 index 0000000..28baec0 --- /dev/null +++ b/shreddit/util.py @@ -0,0 +1,24 @@ +"""This module contains common utilities for the rest of the package. +""" +import random + + +WORDLIST = "/usr/share/dict/words" +STATIC_TEXT = "I have been Shreddited for privacy!" + + +try: + from loremipsum import get_sentence +except ImportError: + def get_sentence(): + """This keeps the mess of dealing with the loremipsum library out of the shredding code. Until the maintainer of + the loremipsum package uploads a version that works with Python 3 to pypi, it is necessary to provide a drop-in + replacement. The current solution is to return a static text string unless the operating system has a word list. + If that is the case, use it instead. + """ + try: + lines = [line.strip() for line in open(WORDLIST).readlines()] + return " ".join(random.sample(lines, random.randint(50, 150))) + except IOError: + # The word list wasn't available... + return STATIC_TEXT