Printing a word from a file that is misspelled in Python

时间:2017-04-10 01:12:36

标签: python

So I am looking to print out the words from a sample file that are misspelled and I cant seem to figure out how to loop through 2 lists together. Here's the code: (the top is just a helper function) and dict.txt is just a long list of every possible word

def cleanWords(wlist):
    ret=[]
    for word in wlist:
        cleanword = word.strip('?.,;:!\'-"\n()')
        ret.append(cleanword.lower())
    return ret

f = open('dict.txt', 'r')
lines = f.readlines()
cleanlistdic = cleanWords(lines)

inword = raw_input("Enter a file name: ")
g = open(inword, 'r')
lines2 = g.readlines()
cleanlistfile = cleanWords(lines2)

# this part is where i get stuck
for line in cleanlistfile:
    for j in cleanlistdic:
        if line not in cleanlistdic:
            print line

2 个答案:

答案 0 :(得分:0)

You inner loop is pointless (as evidenced by you never using j).

You just need the single loop: for each line, print it if it is not in cleanlistdic.

答案 1 :(得分:0)

You can use list comprehension to accomplish this task:

desired_lines = [line for line in cleanlistfile if line not in cleanlistdic]

If you to print each line, you can use a for loop:

for line in desired_lines:
     print line