Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loading a textfile in python and sorting every word by alphabet as the output of a dictionary:

Following function is required: A textfile, which needs to be read into Python, and the words have to be sorted by alphabetic order as an output into a dictionary.

A given textfile:

Im about to go to the movies on Monday!
And Im very excited to go.

Following code reads the file and removes unecessary characters:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def movietext():
    with open("movietext.txt", "r") as textfile:
     text = textfile.read()
     for char in "!":
         text=text.replace(char,"")
     return text
print(movietext())

Which results in the following:

Im about to go to the movies on Monday
And Im very excited to go

The requirement from this is to get a dictionary printed out as following:

And: 1
about: 1
excited: 1
go: 1
Im: 2
Monday: 1
movies: 1
on: 1
the: 1
to: 3
very: 1

Very thankful for any kind of help on solving this.

>Solution :

You can utilize a few of Python’s built-in functions, sorted(), zip() and map():

string = '''Im about to go to the movies on Monday
And Im very excited to go'''

words = string.split()
words2 = sorted(set(words))

for key, value in zip(words2, map(words.count, words2)):
    print(f"{key}: {value}")

Output:

And: 1
about: 1
excited: 1
go: 1
Im: 2
Monday: 1
movies: 1
on: 1
the: 1
to: 3
very: 1

Explanation:

As you know, words = string.split() takes the string string and stores every substring separated by a space into the list words.

The line

words2 = sorted(set(words))

removes any duplicate words, sorts them, and stores the resulting list into the variable words2.

Finally, the line

zip(words2, map(words.count, words2))

maps every word in the sorted list to the list.count() method (where the list is the original list that contains the duplicate words), and prints out the counts next to their corresponding word.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading