Importing Random Words From A File Without Duplicates Python
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
Solution 1:
Make WordList
a set
:
WordList = set()
Then update
that set instead of appending:
WordList.update(set([RandWrd]))
Of course WordList
would be a bad name for a set.
There are a few other problems though:
- Don't use uppercase names for variables and functions (follow PEP8)
- What happens if you draw the same word twice in your loop? There is no guarantee that
WordList
will contain 10 items after the loop completes, if words may appear multiple times.
The latter might be addressed by changing your loop to:
while len(WordList) < 10:
FileLines = open(FileSelection).read().splitlines()
RandWrd = random.choice(FileLines)
WordList.update(set([RandWrd]))
You would have to account for the case that there don't exist 10 distinct words after all, though.
Even then the loop would still be quite inefficient as you might draw the same word over and over and over again with random.choice(FileLines)
. But maybe you can base something useful off of that.
Solution 2:
not sure i understand you right, but ehehe, line 3: "if wrdcount" . . where dit you give wrdcount a value ? Maybe you intent something along the line below?:
wordset = {}
wrdcount = len(wordset)
while wrdcount < 10:
# do some work to update the setcode here
# when end-of-file break
Post a Comment for "Importing Random Words From A File Without Duplicates Python"