python - 如何从以某个字符开头的单词列表中找到一个随机单词?
问题描述
我正在尝试从以某个字母开头的单词列表中检索一个单词。这个字母是通过一个变量 char 指定的。单词列表取自使用请求的在线资源。下面的代码不能正常工作。
def randomword(char):
# use char to find a word from the dictionary
print("The computer is attempting to find a word")
url = "http://www.mieliestronk.com/corncob_lowercase.txt"
res = requests.get(url)
text = res.text
words = [idx for idx in text if idx.lower().startswith(char.lower())]
# find all words that start with char
print(words)
# for some reason this only prints the letter a bunch of times
input("just pausing for no reason")
word = random.choice(words)
clear()
print("The Computers Word: " + word)
return word
我遇到麻烦的部分是从网站上找到所有以某个字母开头的单词。出于某种原因,除了单个字母之外,它无法读取单词。如果可能的话,你能向我解释为什么它把单词读成单个字母,以及如何阻止它!我试图避免使用 BeautifulSoup 和其他类似的东西,以便我可以自学 python,但我无法解决这个问题来挽救我的生命。
解决方案
您缺少 a split
,因此您的列表理解将整个字符串划分为字符。
words = [idx for idx in text.split() if idx.lower()[0] == char.lower()]
推荐阅读
- javascript - 将 html、js 和 python 文件导入快速服务器
- python - 在一个键的多个值的字典中添加列表或字典 - Python
- odoo - 如何在 odoo.conf 中使用环境变量
- angular - 为什么 Angular 组件定义接口?
- javascript - 在 Sails 操作中访问 url 参数
- xamarin - Xamarin.Android.Targets 失败并出现错误“输入字符串的格式不正确。”
- gcc - gcc 链接器如何获取函数的大小?
- android - ViewPager 内的 EpoxyRecyclerView
- javascript - 如果项目与字符串匹配,请检查 localStorage
- haskell - 如何处理需要额外类型约束的类型类实例