2

I would like to define a function scaryDict() which takes one parameter (a textfile) and returns the words from the textfile in alphabetical order, basically produce a dictionary but does not print any one or two letter words.

Here is what I have so far...it isn't much but I don't know the next step

def scaryDict(fineName):

    inFile = open(fileName,'r')
    lines = inFile.read()
    line = lines.split()
    myDict = {}
    for word in inFile:
        myDict[words] = []
        #I am not sure what goes between the line above and below
    for x in lines:
        print(word, end='\n')
bnjmn
  • 4,508
  • 4
  • 37
  • 52
Othman
  • 33
  • 3

4 Answers4

1

You are doing fine till line = lines.split(). But your for loop must loop through the line array, not the inFile.

for word in line:
    if len(word) > 2: # Make sure to check the word length!
        myDict[word] = 'something'

I'm not sure what you want with the dictionary (maybe get the word count?), but once you have it, you can get the words you added to it by,

allWords = myDict.keys() # so allWords is now a list of words

And then you can sort allWords to get them in alphabetical order.

allWords.sort()
slider
  • 12,810
  • 1
  • 26
  • 42
0

I would store all of the words into a set (to eliminate dups), then sort that set:

#!/usr/bin/python3

def scaryDict(fileName):
    with open(fileName) as inFile:
         return sorted(set(word
                          for line in inFile
                          for word in line.split()
                          if len(word) > 2))

scaryWords = scaryDict('frankenstein.txt')
print ('\n'.join(scaryWords))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

Also keep in mind as of 2.5 the 'with' file contains an enter and exit methods which can prevent some issues (such as that file never getting closed)

with open(...) as f:
    for line in f:
        <do something with line>

Unique set

Sort the set

Now you can put it all together.

Community
  • 1
  • 1
crownedzero
  • 496
  • 1
  • 7
  • 18
0

sorry that i am 3 years late : ) here is my version

def scaryDict():
    infile = open('filename', 'r') 
    content = infile.read()
    infile.close()

    table = str.maketrans('.`/()|,\';!:"?=-', 15 * ' ')
    content = content.translate(table)

    words = content.split()
    new_words = list()

    for word in words:
        if len(word) > 2:
            new_words.append(word)

    new_words = list(set(new_words))
    new_words.sort()

    for word in new_words:
        print(word)
redx21
  • 11
  • 3