python - 按字符长度从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()
无论字符长度如何,函数都基本返回随机单词。
解决方案
您可以使用最佳数据结构(列表字典)来解决此问题。
更新代码:
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()
推荐阅读
- xml - Odoo 10:安全访问自定义模块
- sql-server - 搜索电子邮件仅包含 X 字符的行
- java - 服务完成后如何禁用按钮?
- sql - DB2如何找到两个在同一日期活跃的用户
- postgresql - 将 Google CloudSQL Postgres 数据库连接到 Data Studio
- php - 致命错误:未捕获的 Facebook\WebDriver\Exception\UnknownServerException:等待驱动程序服务器以 ChromeDriver 和 Selenium 启动时超时
- shell - 搜索两个分号之间的字符串(值)并拆分为行
- android-fragments - 在格式化 Recyclerview 的数据时遇到问题
- hibernate - 如何从jpa entitymanager为psql“设置时区”?
- php - Rss 提要不返回来自数据库的所有行