首页 > 解决方案 > 按字符长度从txt文件中的列表中提取随机单词

问题描述

我的任务是从用户输入定义的文本文件(在同一路径中)中提取一个随机单词。文件的每一行都有一个字符串:

Lilongwe
Male
Bamako
Valletta
Majuro
Nouakchott
Chisinau
Monaco

与代码斗争:

import random

file = "file.txt"


def random_list(file):
    list_of_words = []
    with open(file) as words:
        for line in words:
            list_of_words.append(line.replace("\n", ""))
    return list_of_words


list_of_words = random_list(file)
# print(list_of_words)

user_input = input("1. up to 4 letters\n2. 5 -8 letters\n3. 9-16 letters\n--> ")

def diff_level():
    if user_input == "1":
        while len(list_of_words) > 4:
            pulled_word = random.choice(list_of_words)
            print(pulled_word)
            break
    elif user_input == "2":
        while len(list_of_words) > 8:
            pulled_word = random.choice(list_of_words)
            print(pulled_word)
            break
    elif user_input != "2" or "1":
        while len(list_of_words) > 16:
            pulled_word = random.choice(list_of_words)
            print(pulled_word)
            break

diff_level() 

无论字符长度如何,函数都基本返回随机单词。

标签: python

解决方案


您可以使用最佳数据结构(列表字典)来解决此问题。

更新代码:

import random

file = "file.txt"


def random_list(file):
    words = {'upto_4': [], 'upto_8': [], 'upto_16': []}
    with open(file) as words:
        for line in words:
            if len(words) <= 4:
                words['upto_4'].append(line.replace("\n", ""))
            elif len(words) <= 8:
                words['upto_8'].append(line.replace("\n", ""))
            elif len(words) <= 16:
                words['upto_16'].append(line.replace("\n", ""))
    return list_of_words


words = random_list(file)
# print(list_of_words)

user_input = input("1. up to 4 letters\n2. 5 -8 letters\n3. 9-16 letters\n--> ")

def diff_level():
    if user_input == "1":
        pulled_word = random.choice(words['upto_4'])
        print(pulled_word)
    elif user_input == "2":
        pulled_word = random.choice(words['upto_8'])
        print(pulled_word)
    elif user_input != "2" or "1":
        pulled_word = random.choice(words['upto_16'])
        print(pulled_word)

diff_level() 

推荐阅读