Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Can someone convert this Python 2 code into Python 3 code? **Code:** import re import sys import collections from operator import itemgetter def clean_words(words):

Can someone convert this Python 2 code into Python 3 code?

**Code:**

import re import sys import collections from operator import itemgetter

def clean_words(words): """ Removes anything but letters in word list""" cleaned = []

for i in xrange(len(words)): word = re.sub(r"[^a-zA-Z]", '', words[i]) if len(word) > 0: cleaned.append(word)

return cleaned

def book_to_wordlist(filename): """ Converts a text file to words list. """ words = [] # open book with open(filename, 'r') as _f: # read into buffer split into words and return words = clean_words( _f.read().split(" ") )

return words

def print_histo(top_20_words): """ Prints a histogram of top 20 words """ max_repeat = list( max(top_20_words, key=itemgetter(1)) )[1]

for tup in top_20_words: print "%s " % (tup[0]), # 20 *s for largest for i in xrange(tup[1] * 20 / max_repeat): sys.stdout.write("*")

print

def main(): books = [ "around_world.txt", "republic.txt", "three_musketeers.txt", "walden.txt" ]

# For each of these texts perform the following tasks for book in books: # Create a list of 20 words most frequently appearing words = book_to_wordlist(book) counter = collections.Counter(words) top20 = counter.most_common(20) print book # Plot frequencies of all words appearing in the text print_histo(top20) print

if __name__ == "__main__": main()

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Case Studies In Business Data Bases

Authors: James Bradley

1st Edition

0030141346, 978-0030141348

More Books

Students also viewed these Databases questions

Question

Finding and scheduling appointments with new prospective clients.

Answered: 1 week ago