【问题标题】:How to print a random item from a dictionary that is in a text file on Python?如何从 Python 文本文件中的字典中打印随机项目?
【发布时间】:2022-12-16 22:20:10
【问题描述】:

所以我有一本字典,里面有一堆单词作为键,它们的定义作为值。

例如,word_list.txt

words = {
happy: "feeling or showing pleasure or contentment.", 
apple: "the round fruit which typically has thin green or red skin and crisp flesh.", 
today: "on or in the course of this present day."
faeces: "waste matter remaining after food has been digested, discharged from the bowels; excrement."
}

如何打印 Python 文本文件中字典中的随机单词?

【问题讨论】:

  • print(random.choice(words.keys()))
  • 因为它目前代表 words 不是有效的字典
  • 是的,word_list.txt 需要带引号的键和在 today 的值之后的逗号才能成为有效的 Python。
  • 欢迎来到堆栈溢出!您似乎在要求某人为您编写一些代码。 Stack Overflow 是一个问答网站,而不是代码编写服务。请查看How to Ask 了解如何编写有效的问题。

标签: python


【解决方案1】:

一种方法

import random
    words = {
    "happy": "feeling or showing pleasure or contentment.", 
    "apple": "the round fruit which typically has thin green or red skin and crisp flesh.", 
    "today": "on or in the course of this present day.",
    "faeces": "waste matter remaining after food has been digested, discharged from the bowels; excrement."
    }
    
    id = random.sample(words.keys(),1)
    print(words[id[0]])

【讨论】:

    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多