Skip to content

Instantly share code, notes, and snippets.

@NABEF9
Last active October 24, 2018 02:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NABEF9/9516c6431878aafa2c2c238790fd17ab to your computer and use it in GitHub Desktop.
Save NABEF9/9516c6431878aafa2c2c238790fd17ab to your computer and use it in GitHub Desktop.
Randomizer
#RANDOMIZER.PY - created by Steven C Mills 2018 | www.stevencmills.ca
#Most recent update was Oct 23, 2018: Now with loops and an exit option!
#Ensure "soundtrack.txt" and "books.txt" are stored in the same folder as "Randomizer.py"
# Import extensions
import random
# Print a time-related greeting
import datetime
currentTime = datetime.datetime.now()
currentTime.hour
0
if currentTime.hour < 12:
print('Good morning!')
elif 12 <= currentTime.hour < 18:
print('Good afternoon!')
else:
print('Good evening!')
# Open a txt file and print a random line without deleting it
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
# Open a txt file and print a random line, then delete
k = 1
filename = 'soundtrack.txt'
with open(filename) as file:
lines = file.read().splitlines()
if len(lines) >= 1:
random_lines = random.sample(lines, k)
album = ("\n".join(random_lines)) # print random lines
with open(filename, 'w') as output_file:
output_file.writelines(line + "\n"
for line in lines if line not in random_lines)
elif lines: # file is too small
print("\n".join(lines)) # print all lines
with open(filename, 'wb', 0): # empty the file
pass
#Identify variables. User can edit items on "todos" line - ensure formatting retained
book = random_line('books.txt')
todos = ['reading one chapter of nonfiction', 'handwriting one of Walt Whitman\'s poems', 'doing 30 minutes of songwriting', 'learning one lesson on free Code Camp', 'doing one guitar lesson']
todo = random.choice(todos)
music = 'Today\'s soundtrack is "%s."' % album
activity = 'Your activity today is %s. ' % todo
#if activity is reading, the program will display a random line from books.txt
if todo == 'reading one chapter of nonfiction':
activity = activity + 'You will read one chapter from "%s."' % book
end = 'Have a great day!'
#Ask user if homework completed yet
asking = True
homework = input('\nHave you done your homework for this week? (y/n) ')
while asking == True:
if homework.lower() == 'y':
asking = False
print('\n' + music + '\n\n' + activity + '\n\n' + end)
break
if homework.lower() == 'n':
asking = False
print('\n' + music + '\n\nYour activity today is completing one section of homework.\n\n'+ end)
break
elif homework != 'y' or 'n':
homework = input('Unknown value. Enter Y for YES or N for NO: ')
asking = True
#Give user option to quit program
quitting = input('\nAll done? Type \"Q\" to quit! ')
if quitting.lower() == 'q':
exit()
@bucknerns
Copy link

bucknerns commented Oct 7, 2018

Saw your reddit post, I would do something closer to this.

import random
from tkinter import Tk, messagebox
import datetime
root = Tk()
root.withdraw()

todos = [
    "doing 30 minutes of songwriting",
    "doing one guitar lesson",
    "handwriting one of Walt Whitman's poems",
    "learning one lesson on free Code Camp",
    "reading one chapter of nonfiction"]


def get_random_lines(filename, delete=False, count=1):
    """Get a random line from text file
    https://www.w3resource.com/python-exercises/file/python-io-exercise-15.php
    """
    with open(filename) as fp:
        lines = fp.read().splitlines()
    if len(lines) < count:
        random_lines = lines
    else:
        random_lines = random.sample(lines, count)
    if delete:
        with open(filename, "w") as fp:
            fp.write("\n".join(l for l in lines if l not in random_lines))
    return random_lines


def get_random_line(filename, delete=False):
    return (get_random_lines(filename, delete, 1) or [None])[0]


def build_msg():
    hour = datetime.datetime.now().hour
    msg = "Good {0}!".format(
        "morning" if hour < 12 else "afternoon" if hour < 18 else "evening")
    msg += '\n\nToday\'s soundtrack is "{0}."'.format(
        get_random_line("soundtrack.txt", delete=True))
    todo = random.choice(range(len(todos)))
    activity = "\n\nYour activity today is {0}. ".format(todos[todo])
    if todo == 4:
        activity += 'You will read one chapter from "{0}".'.format(
            get_random_line('books.txt'))
    msg += activity
    msg += "\n\nHave a great day!"
    return msg


messagebox.showinfo("Randomizer", build_msg())

@NABEF9
Copy link
Author

NABEF9 commented Oct 24, 2018

Thanks for the great tips, Bucknerns! That's beautiful!

Saw your reddit post, I would do something closer to this.

import random
from tkinter import Tk, messagebox
import datetime
root = Tk()
root.withdraw()

todos = [
    "doing 30 minutes of songwriting",
    "doing one guitar lesson",
    "handwriting one of Walt Whitman's poems",
    "learning one lesson on free Code Camp",
    "reading one chapter of nonfiction"]


def get_random_lines(filename, delete=False, count=1):
    """Get a random line from text file
    https://www.w3resource.com/python-exercises/file/python-io-exercise-15.php
    """
    with open(filename) as fp:
        lines = fp.read().splitlines()
    if len(lines) < count:
        random_lines = lines
    else:
        random_lines = random.sample(lines, count)
    if delete:
        with open(filename, "w") as fp:
            fp.write("\n".join(l for l in lines if l not in random_lines))
    return random_lines


def get_random_line(filename, delete=False):
    return (get_random_lines(filename, delete, 1) or [None])[0]


def build_msg():
    hour = datetime.datetime.now().hour
    msg = "Good {0}!".format(
        "morning" if hour < 12 else "afternoon" if hour < 18 else "evening")
    msg += '\n\nToday\'s soundtrack is "{0}."'.format(
        get_random_line("soundtrack.txt", delete=True))
    todo = random.choice(range(len(todos)))
    activity = "\n\nYour activity today is {0}. ".format(todos[todo])
    if todo == 4:
        activity += 'You will read one chapter from "{0}".'.format(
            get_random_line('books.txt'))
    msg += activity
    msg += "\n\nHave a great day!"
    return msg


messagebox.showinfo("Randomizer", build_msg())

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