Skip to content

Instantly share code, notes, and snippets.

@Chris--B
Created November 9, 2012 04:03
Show Gist options
  • Save Chris--B/4043632 to your computer and use it in GitHub Desktop.
Save Chris--B/4043632 to your computer and use it in GitHub Desktop.
from functools import reduce
from operator import add
#Doesn't handle whitespace padding well
def countWords(s):
return len(s.split(' '))
def stopLooping():
global looping
looping = False
print('Bye!')
def wordsInLine():
s = input('Line? ')
print('You typed %s words\n' % countWords(s))
def readFile():
global lines
filename = input('Filename? ')
try:
with open(filename, 'r') as f:
lines = f.readlines()
except IOError as e:
print(str(e))
return
print('There are %s lines in %s.' % (len(lines), filename))
def writeFile():
if lines is None:
print('You should try option 2 first.')
return
filename = input('Filename? ')
lengths = [countWords(line) for line in lines]
with open(filename, 'w') as f:
for pair in zip(lengths, lines):
f.write('%03d %s' % pair)
print('There are %s words in %s' % (reduce(add, lengths, 0), filename))
looping = True
lines = None
def main():
menu = {'0' : ('Exit', stopLooping),
'1' : ('Count words in a line.', wordsInLine),
'2' : ('Read the file into memory.', readFile),
'3' : ('Write a numbered file.', writeFile) }
while looping:
for num, (label, _) in sorted(menu.items()):
print('%s) %s' % (num, label))
print()
user_in = input('> ')
if user_in in menu:
menu[user_in][1]()
else:
print('Sorry, not an option.')
print('')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment