0
def scary(filename):
infile = open(filename, 'r')
content = infile.read()
infile.close()
for i in ';",.()[]{}\/0123456789@#!$':
    content = content.replace(i, ' ')
words = content.split()
d = {}
for word in words:
    if word in d:
        continue
    else:
        d[words] = words
lst = []
for n in d:
    lst.append(n)
    lst.sort()
outfile = open('dictionary.txt', 'w')
for words in lst:
    outfile.write(words + '\n')
outfile.close()

I am suppose to write a function scary() that reads in an electronic version of a scary book (it could be any book), picks up all the words in it and writes them in alphabetic order in a new file called dictionary.txt.

Edited by Reverend Jim: Fixed formatting

4
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by pyTony
0

Please wrap your program in [code] Your program goes here [/code] tags. Otherwise we can't see how the lines in your program are indented and have to guess.

0
def scary(filename):
    infile = open(filename, 'r')
    content = infile.read()
    infile.close()
    for i in ';",.()[]{}\/0123456789@#!$':
        content = content.replace(i, ' ')
    words = content.split()
    d = {}
    for word in words:
        if word in d:
            continue
        else:
            d[words] = words
    lst = []
    for n in d:
        lst.append(n)
        lst.sort()
    outfile = open('dictionary.txt', 'w')
    for words in lst:
        outfile.write(words + '\n')
    outfile.close()

Edited by br0wnm4n: n/a

0
for word in words:
        if word in d:
            continue
        else:
            #d[words] = words This is wrong. You want word, not words
            d[word] = word #This should work
0

Excuse me for butting in, but this is poor style. Try instead:

for word in words:
        if word not in d:
            d[word] = word
0

For code clean up I would take also this block of code:

lst = []
    for n in d:
        lst.append(n)
        lst.sort()

Question to OP: how many times lst is sorted?

I would think that instead of

for word in words:
        if word not in d:
            d[word] = word

I would change data type to set as I see no purpose to use dict:

d = set(words)

Seeing that the n in d goes only through the keys anyway.


First block my version:

lst=sorted(d)

Edited by pyTony: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.