从文件中导入随机单词,没有重复的Python [英] importing random words from a file without duplicates Python

查看:109
本文介绍了从文件中导入随机单词,没有重复的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序,该程序从包含10个以上单词的文本文件中选择10个单词.出于程序目的,从文本文件导入这10个单词时,我不能两次导入相同的单词!目前,我正在为此使用一个列表,但是似乎出现了相同的单词.我对集合有一定的了解,知道它们不能两次拥有相同的值.到目前为止,我对如何解决此问题一无所知,将不胜感激.谢谢!

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 list for this however the same words seem to appear. 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!

请在下面找到相关代码! -(p.s. FileSelection基本上是打开文件对话框)

please find relevant code below! -(p.s. FileSelection is basically open file dialog)

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

推荐答案

使WordList一个set:

WordList = set()

然后设置update而不是附加:

WordList.update(set([RandWrd]))

当然WordList对于集合来说是个坏名字.

Of course WordList would be a bad name for a set.

但是还有其他一些问题:

There are a few other problems though:

  • 请勿对变量和函数使用大写名称(请遵循 PEP8 )
  • 如果在循环中两次绘制相同的单词会发生什么?如果单词可能出现多次,则不能保证循环结束后WordList将包含10个项目.
  • 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]))

尽管如此,您还是不得不考虑根本不存在10个不同的单词的情况.

You would have to account for the case that there don't exist 10 distinct words after all, though.

即使那样,循环仍然会非常低效,因为您可能会用random.choice(FileLines)一遍又一遍地绘制相同的单词.但是也许您可以从中得出一些有用的信息.

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.

这篇关于从文件中导入随机单词,没有重复的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆