diff options
author | Clayton G. Hobbs <clay@lakeserv.net> | 2016-02-04 12:58:18 -0500 |
---|---|---|
committer | Clayton G. Hobbs <clay@lakeserv.net> | 2016-02-04 12:58:18 -0500 |
commit | 9b9cc013ab324b98fcb3ec883c97d57df232a808 (patch) | |
tree | e46da9be20dd422b70910ecbb50fcb9a84db9f19 | |
parent | d36b65890a925c3de87dfc103b4e2279d9b33eb1 (diff) |
Open all files using with blocks
I truly am a modern Python man.
-rwxr-xr-x | kaylee.py | 24 | ||||
-rw-r--r-- | languageupdater.py | 14 |
2 files changed, 18 insertions, 20 deletions
diff --git a/kaylee.py b/kaylee.py index de5c7c4..4774137 100755 --- a/kaylee.py +++ b/kaylee.py @@ -73,15 +73,13 @@ class Kaylee: def create_strings_file(self): # Open the strings file - strings = open(self.config.strings_file, "w") - # Add command words to the corpus - for voice_cmd in sorted(self.commands.keys()): - strings.write(voice_cmd.strip().replace('%d', '') + "\n") - # Add number words to the corpus - for word in self.number_parser.number_words: - strings.write(word + "\n") - # Close the strings file - strings.close() + with open(self.config.strings_file, 'w') as strings: + # Add command words to the corpus + for voice_cmd in sorted(self.commands.keys()): + strings.write(voice_cmd.strip().replace('%d', '') + "\n") + # Add number words to the corpus + for word in self.number_parser.number_words: + strings.write(word + "\n") def log_history(self, text): if self.options['history']: @@ -91,11 +89,9 @@ class Kaylee: self.history.pop(0) # Open and truncate the history file - hfile = open(self.config.history_file, "w") - for line in self.history: - hfile.write(line + "\n") - # Close the file - hfile.close() + with open(self.config.history_file, 'w') as hfile: + for line in self.history: + hfile.write(line + '\n') def run_command(self, cmd): """Print the command, then run it""" diff --git a/languageupdater.py b/languageupdater.py index 035bee4..98397c7 100644 --- a/languageupdater.py +++ b/languageupdater.py @@ -47,17 +47,19 @@ class LanguageUpdater: host = 'http://www.speech.cs.cmu.edu' url = host + '/cgi-bin/tools/lmtool/run' - # Prepare request - files = {'corpus': open(self.config.strings_file, 'rb')} - values = {'formtype': 'simple'} + # Submit the corpus to the lmtool + response_text = "" + with open(self.config.strings_file, 'rb') as corpus: + files = {'corpus': corpus} + values = {'formtype': 'simple'} - # Send corpus to the server - r = requests.post(url, files=files, data=values) + r = requests.post(url, files=files, data=values) + response_text = r.text # Parse response to get URLs of the files we need path_re = r'.*<title>Index of (.*?)</title>.*' number_re = r'.*TAR([0-9]*?)\.tgz.*' - for line in r.text.split('\n'): + for line in response_text.split('\n'): # If we found the directory, keep it and don't break if re.search(path_re, line): path = host + re.sub(path_re, r'\1', line) |