DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Python from scratch- The journey continues

Python from scratch- The journey continues

Hod Benbinyamin user avatar by
Hod Benbinyamin
·
Mar. 26, 12 · Interview
Like (0)
Save
Tweet
Share
4.38K Views

Join the DZone community and get the full member experience.

Join For Free

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()

Python (language) Scratch (programming language)

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • PHP vs React
  • Top 5 Java REST API Frameworks
  • Key Considerations When Implementing Virtual Kubernetes Clusters
  • Quick Pattern-Matching Queries in PostgreSQL and YugabyteDB

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: