python - I have a problem the random.choice() function as it prints one LETTER in a list of WORDS
问题描述
I am new to python and programming in general and I was trying to make a hangman game. I downloaded a dictionary text file and opened it in pycharm and I applied the random.choice() function on it and it only printed a letter of a random word in the .txt file:
import random
f = open ("/home/ar/Downloads/sowpods.txt")
sowpods = f.read()
sowpods = random.choice(sowpods)
print(sowpods)
解决方案
You first need to convert from a list of characters to a list of words. You can do this using string.split()
.
import random
f = open ("/home/ar/Downloads/sowpods.txt")
sowpods = f.read().split()
sowpods = random.choice(sowpods)
print(sowpods)
推荐阅读
- java - 为什么没有“volatile”的程序会像“volatile”一样工作?
- python - 我有一个不同类型(int 和 str)的 split() 输入,当我尝试执行数学运算时,我收到一条错误消息
- vaadin - Vaadin 14 应用程序未加载导致空白页面的 cache.js 文件
- java - 在android中使用自定义相机拍照后如何将图片存储在同一个应用程序中,如图库
- java - openssl_encrypt($string, $encrypt_method, $key, 0, $iv) 在java中等效的php函数?
- google-chrome-extension - 如何设置 Youtube 视频的音量?
- php - 使用 where in 条件从表中获取最新的 N 条记录
- asp.net-core - 将 OpenID Connect 与 .NET Core 3.0 ASP.NET Core API 服务一起使用时出错
- php - 正则表达式删除损坏的图像 url
- vuejs2 - 如何在 vue2 中添加条带元素?