The code is supposed to ask a user for a file, find all the unique words in the file and sort them in a list alphabetically. However for each run,the return output is always "None".
I've tried indenting the for loop "for x in unique" under the first for loop but the outcome is the same. I haven't tried much else cause I'm not really sure what the issue is .
inp=input('Enter file: ')
fhand=open(inp)
for line in fhand:
words=line.split()#List containing all the words in the line
unique=list()#List which will store all the unique words in the file
for word in words:#For each word in list containing the words in the line
if words.count(word)==1:
unique.append(word)#To add the word to the unique list
else:
continue
for x in unique:#For each word in the unique list
y=unique.count(x)
if y==1:
continue
else:
for y in unique: #This loop is to remove all duplicates from the the unique list
unique.remove(x)
print(unique.sort())
CodePudding user response:
Why not set
? What I can think of is something like what follows:
inp=input('Enter file: ')
fhand=open(inp).read()
sorted(set(fhand.split()))
CodePudding user response:
The problem in the code is that you are declaring the variable unique inside the for each loop, and hence the interpreter does not find any variable named 'unique' outside the for each loop.
Here's the modified code
inp=input('Enter file: ')
fhand=open(inp)
unique=list()
for line in fhand:
words=line.split()#List containing all the words in the line
for word in words:#For each word in list containing the words in the line
if words.count(word)==1:
unique.append(word)#To add the word to the unique list
else:
continue
for x in unique:#For each word in the unique list
y=unique.count(x)
if y==1:
continue
else:
for y in unique: #This loop is to remove all duplicates from the the unique list
unique.remove(x)
print(unique.sort())