Python 如何从以某个字符开头的单词列表中查找随机单词?
我试图从以某个字母开头的单词列表中检索一个单词。此字母通过变量char指定。单词列表是使用请求从在线来源获取的。下面的代码无法正常工作Python 如何从以某个字符开头的单词列表中查找随机单词?,python,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/
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,但我无法找出这一点来挽救我的生命。您缺少一个
拆分
,因此您对列表的理解将整个字符串拆分为字符
words = [idx for idx in text.split() if idx.lower()[0] == char.lower()]
打印(文字)
的输出是什么?我想你得把话说清楚谢谢!我很难理解为什么这么简单的事情会让我如此艰难。Split是一个在这之前我并不真正理解的命令!谢谢你的帮助!