首页 > 解决方案 > 如何从以某个字符开头的单词列表中找到一个随机单词?

问题描述

我正在尝试从以某个字母开头的单词列表中检索一个单词。这个字母是通过一个变量 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,但我无法解决这个问题来挽救我的生命。

标签: python

解决方案


您缺少 a split,因此您的列表理解将整个字符串划分为字符。

    words = [idx for idx in text.split() if idx.lower()[0] == char.lower()]

推荐阅读