Modernize Python 2 code to get ready for Python 3

This commit is contained in:
cclauss
2018-03-21 21:41:35 +01:00
parent d521abd5d7
commit 1fa9eb3c2b
42 changed files with 169 additions and 112 deletions

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env python
from __future__ import print_function
import re, string, sys
with open("../stop_words.txt") as f:
@@ -22,7 +23,7 @@ def quit_handler(args):
def upload_get_handler(args):
return "Name of file to upload?", ["post", "file"]
def upload_post_handler(args):
def create_data(filename):
if filename in data:
@@ -32,7 +33,7 @@ def upload_post_handler(args):
for w in [x.lower() for x in re.split("[^a-zA-Z]+", f.read()) if len(x) > 0 and x.lower() not in stops]:
word_freqs[w] = word_freqs.get(w, 0) + 1
word_freqsl = word_freqs.items()
word_freqsl.sort(lambda x, y: cmp(y[1], x[1]))
word_freqsl.sort(key=lambda x: x[1], reverse=True)
data[filename] = word_freqsl
if args == None:
@@ -49,7 +50,7 @@ def word_get_handler(args):
if word_index < len(data[filename]):
return data[filename][word_index]
else:
return ("no more words", 0)
return ("no more words", 0)
filename = args[0]; word_index = args[1]
word_info = get_word(filename, word_index)
@@ -57,16 +58,16 @@ def word_get_handler(args):
rep += "\n\nWhat would you like to do next?"
rep += "\n1 - Quit" + "\n2 - Upload file"
rep += "\n3 - See next most-frequently occurring word"
links = {"1" : ["post", "execution", None],
"2" : ["get", "file_form", None],
links = {"1" : ["post", "execution", None],
"2" : ["get", "file_form", None],
"3" : ["get", "word", [filename, word_index+1]]}
return rep, links
# Handler registration
handlers = {"post_execution" : quit_handler,
"get_default" : default_get_handler,
"get_file_form" : upload_get_handler,
"post_file" : upload_post_handler,
"get_default" : default_get_handler,
"get_file_form" : upload_get_handler,
"post_file" : upload_post_handler,
"get_word" : word_get_handler }
# The "server" core
@@ -81,7 +82,7 @@ def handle_request(verb, uri, args):
# A very simple client "browser"
def render_and_get_input(state_representation, links):
print state_representation
print(state_representation)
sys.stdout.flush()
if type(links) is dict: # many possible next states
input = sys.stdin.readline().strip()