0

running into an issue. (doing a review for upcoming exam). The first question asked me to print the amount of words in each line of text, to the output file. This was an easy task. (ill provide the code i used). Another similar question was just, print the amount (count) of unique words in each line of text. The furthest i was able to get was appending words into a list, and printing the length of the list... but it ends up adding each iteration. So it would print 7,14,21. Instead of 7,7,7 (just as an example to help exapain) How would i go about fixing this code to behave properly? I've been trying for the last 30 minutes. Any help would be appreciated!

code for number of words in each line:

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    for line in inf:
        wordlst = line.split()
        count = len(wordlst)
        outf.write(str(count)+'\n')

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')

code for number of unique words in each line (failure):

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    unique = []
    for line in inf:
        wordlst = line.split()
        for word in wordlst:
            if word not in unique:
                unique.append(word)
        outf.write(str(len(unique)))

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')
1
  • Define unique inside your for loop over the lines Commented Mar 26, 2017 at 22:55

1 Answer 1

2

If the first one works try set:

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    for line in inf:
        wordlst = line.split()
        count = len(set(wordlst))
        outf.write(str(count)+'\n')

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')
Sign up to request clarification or add additional context in comments.

4 Comments

oh..... well that was a lot easier than what i was trying to do LOL. thanks a lot!
@RoryDaulton Thanks for the heads-up. I haven't posted any question yet but will keep your advice in mind :)
@RyanKelly: On this site, show your appreciation by upvoting all the useful answers. You do that by clicking the up-arrow at the top-left of the answer. In addition, accept the best answer (if it actually answers your question) by clicking the checkmark near the top-left of the answer. That is better than saying thanks in a comment. It also helps others to see that your question was answered.
@zipa: Oops, obviously I meant that comment for Ryan Kelly, not for you. I tried to help you out, and I messed up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.