简体   繁体   English

Python中来自外部文件的随机词生成器

[英]Random word generator from external file in Python

I'm trying to create a small program to allocate words randomly to describe a tree.我正在尝试创建一个小程序来随机分配单词来描述一棵树。 For some reason only the first letter of the word is printed.出于某种原因,只打印了单词的第一个字母。 The "words.txt" file contains ~ 3000 adjectives. “words.txt”文件包含约 3000 个形容词。 Please advise on how to print the full word.请告知如何打印完整的单词。 I've been trying to figure this out for a while and cannot find a solution.我一直在尝试解决这个问题,但找不到解决方案。

Here is the code:这是代码:

import random


def a_word():
    file = open('words.txt', 'r')
    random_word = random.choice(file.readline())
    print('The %s tree.' % random_word)
    return


a_word()

If words.txt look like如果 words.txt 看起来像

first
second

change your code to:将您的代码更改为:

import random


def a_word():
    file = open('words.txt', 'r')
    random_word = random.choice(file.readlines())
    print('The %s tree.' % random_word)
    return


a_word()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM