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.

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.

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

Thank you :)

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

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

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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.