繁体   English   中英

如何读取 .txt 文件中的一组特定单词并生成这些单词的随机化器

[英]how to read a specific set of words in .txt file and generate a randomizer of those words

我想打开一个名为 words.txt 的文件,并根据用户输入的数字从 1 到 10 随机生成单词。

library:la biblioteca
school:el colegio,la escuela
restaurant:el restaurante
movie theater:el cine
airport:el aeropuerto
museum:el museo
park:el parque
university:la universidad
office:la oficina,el despacho
house:la casa

有没有办法只阅读单词的“第二”部分,例如第一行。 跳过“library:”,阅读“ la biblioteca ”而不对单词进行硬编码。

with open("words.txt", "r") as infile:
    words = infile.readline().split() #This is the line that needs improvement
    random_word = random.choice(words)
    newKeys = False
    for i in range(10):
        a = random.choice(1, 10)

这是我走了多远,但我知道我的第二行是我必须改变的(可能)抱歉英语不好

以下代码段执行您所描述的操作:

import random

with open("words.txt", "r") as infile:
    words = [line.rstrip().split(":")[1] for line in infile]
    for i in range(10):
        print (random.choice(words))

rstrip()调用对于删除每行末尾的换行符是必要的,而split(":")会在冒号字符处拆分行,因此[1]将返回第二部分。 整个表达式在列表推导中,因此它将在文件的每一行重复,并将结果收集在列表words中。

这很接近。 读取words.txt文件后,可以对字符串使用split()方法,例如:

print("example:1".split(":"))
# ['example', '1']

如果您想打印出“la biblioteca”并跳过“图书馆”:

import random

with open("words.txt", "r") as infile:

    # Read a list of words from the file
    words = infile.read().splitlines()
    # Replace word strings with lists where they've been split on ":"
    words = [word.split(":") for word in words]

    for i in range(10):
        # Choose a random word from the words
        a = random.choice(words)

        # Only print the right portion
        print(a[1])

暂无
暂无

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

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