Arlidio Dobra Arlidio Dobra - 4 years ago 135
Python Question

Choosing random words from a file without duplicates Python (sets)

I'm attempting to create a program which selects 10 words from a text file which contains 10+ words. For the purpose of the program when importing these 10 words from the text file, I must not import the same words twice! Currently I'm utilising a set for this however I'm greeted by a syntax error. I have some knowledge of sets and know they cannot hold the same value twice. As of now I'm clueless on how to solve this any help would be much appreciated. THANKS!

Relevent Code: (FileSelection)= open file dialog

def GameStage03_E():
global WordSet
if WrdCount >= 10:
WordSet = set()
for n in range(0,10):
FileLines = open(FileSelection).read().splitlines()
RandWrd = random.choice(FileLines)
elif WrdCount <= 10:
tkinter.messagebox.showinfo("ERROR", " Insufficient Amount Of Words Within Your Text File! ")

error code:

File "C:\Python34\lib\", line 256, in choice
return seq[i]
`TypeError: 'set' object does not support indexing`

Answer Source

You can just use random.sample (2/3), so you don't have to do that yourself. You also don't need the call to list bigblind's answer suggests, because random.sample can take a set as an argument:

WordSet.update(random.sample(FileLines, 10))

That way, you can replace the entire body of that function with this:

    WordSet.update(random.sample(FileLines, 10))
except ValueError:
    stkinter.messagebox.showinfo("ERROR", "The text file doesn't have enough words!")

I also left out that global statement, which you don't need. It's only necessary if you're assigning a new value to the variable, but all you need to do is call one of its functions, update.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download