我正在尝试从以某个字母开头的单词列表中检索单词。这个字母是通过一个变量 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,但我无法弄清楚这一点来挽救我的生命。
答案 0 :(得分:0)
您缺少一个 split
,因此您的列表解析将整个字符串划分为字符。
words = [idx for idx in text.split() if idx.lower()[0] == char.lower()]