Reputation: 5
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')
Upvotes: 0
Views: 55
Reputation: 27869
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')
Upvotes: 2