Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Python from scratch- The journey continues

DZone's Guide to

Python from scratch- The journey continues

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software


Three weeks ago I published my first post about how I started my journey into
Python.

It was a huge hit and it led me to write a second post about me facing more lessons and more problems on my way to be a Pythoner.

That was 2 weeks ago; I was so eager to read more, to study more, solve issues and eventually write about it.

All this is true but when you have a lack of time it can't happen; to study a  language seriously you need to have time and a clear mind which I didn’t often have at the time since I have my family duties.

Last night finally I found some quiet hours and continue to read Google’s Class Chapter #5- Sorting and Chapter #6- Dictionaries and Files.

The Sorting chapter was actually follow-up of the previous chapter, and for those of you who read my previous post know that I was complaining about the function sorted() not explained at all; well the function has been found in this chapter.

So I read the sorting page and learnt what tuple is and when I came to solve some issues I found out that I had accidentally already solved them while studying the chapter on 'lists'.


From here I jumped into a new page- Dict and files, learned it, memorized it, did all the tasks needed and then my last task was to solve the exercise 'wordcount' (See below). Guys, this exercise was very hard to understand! 
I read the question a few times until I got a sense of what was needed. It got to a point where I became a bit frustrated and I thought about leaving the Google class and moving onto another one.

Somehow after searching through some python sites and getting help, it hit me- The fact that I am looking and reading more sites is a strength that I am developing thanks to the Google search engine. It is a blessing to use Google’s class.

I would like to thank the Python community out there that willing to solve any python issue or help- Just go to Google Search Engine and type- “Python <your question>”


As you may think I was able to eventually finish the test and when I compared my code to the provided solution by Google I found out that they are not that different which is very inspiring.
So here is the question:

# Define print_words(filename) and print_top(filename) functions.
# You could write a helper utility function that reads a file
# and builds and returns a word/count dict for it.
# Then print_words() and print_top() can just call the utility function.
1. For the --count flag, implement a print_words(filename) function that counts how often each word appears in the text and prints:
word1 count1
word2 count2
...
Print the list in order sorted by word (python will sort punctuation to come before letters- that's fine).
Store all the words as lowercase, so 'The' and 'the' count as the same word.
2. For the --topcount flag implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common and so on

Now, the question is a bit longer but I will provide a shortcut for you.
The point that made me lose some valuable time was the fact that nowhere was it specified what the target of this exercise is.

Only when I ran the python command as is and got the following reply I got realized that I should type on the command line --count or --topcount which activates some calculation over a text file of my own.



Understanding the task is a must have key; once you got it, it makes everything easier.
From here it took me around one hour to solve the case and here is my solution (Which is not far from Google’s)
It will be my pleasure to see how you can handle it better.
import sys
def calculate_data (line_data):
# Got a sring and creates dictionary of (word : count)
dict = {}
for word in line_data:
if word in dict:
dict[word] += 1
else:
dict[word] = 1
return dict
def file_to_dict(file1):
# convert file into string by lower case and removing \n
data = file1.read()
data = data.replace ('\n', ' ')
data = data.lower()
# Split by space
for word in data:
line_data = data.split (" ");
# Sending to function that creates and return dictionary
return calculate_data (line_data)
def print_top (filename):
dict1 = {}
file1 = open (filename,'rU')
dict1 = file_to_dict (file1) # convert file into dictionary
# Print the dictionary top20 sorted by values- The solution.
dict1 = sorted(dict1.items(), key=lambda (k,v):(v,k), reverse=True)
for i in range (5):
print dict1[i]
file1.close ()
return filename
def print_words (filename):
dict1 = {}
file1 = open (filename,'rU')
dict1 = file_to_dict (file1) # convert file into dictionary
# Print the dictionary sorted- The solution.
print sorted (dict1.items())
file1.close ()
return filename
def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'
    sys.exit(1)
  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)
if __name__ == '__main__':
  main()

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Hod Benbinyamin. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}