Python 如何从给定字母中筛选单词列表?

Python 如何从给定字母中筛选单词列表?,python,filter,Python,Filter,我有一个python程序,我正在尝试创建,用户可以在其中输入一个字母,该程序过滤掉所有不以这个字母开头的单词。不幸的是,我和我的初学者大脑都不知道如何用代码来写,所以有什么帮助吗 我的代码已经: #Open list of words file and add to "content" variable content = open('Word List').read().splitlines() #Take the first character of every word and make

我有一个python程序,我正在尝试创建,用户可以在其中输入一个字母,该程序过滤掉所有不以这个字母开头的单词。不幸的是,我和我的初学者大脑都不知道如何用代码来写,所以有什么帮助吗

我的代码已经:

#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()
#Take the first character of every word and make a new variable to add that to.
firstchar = [x[0] for x in content]

#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")

不像你看到的那么多,但我很自豪。我想我需要一些使用firstchar[I]和u_selected来匹配这两个字母的东西。

字符串有自己的方法来简化字符串

dir(str)
可以使用.startswith测试字符串的开头。比如说,

words     = open('Word List').read().splitlines()
new_words = [word for word in words if word.startswith('A')]

如上所述,您可以使用[0]访问字符串的第一个字符。如果符合指定的条件,下面的将为您将每个单词添加到新列表中

chosen_words = [word for word in content if word.lower()[0] == u_selected.lower()]

.lower只是将所有内容转换为小写,以确保忽略大小写

以进行筛选,您需要执行以下操作:

打开单词列表文件并添加到内容变量 content=打开“单词列表”。读取.splitlines 询问用户希望使用哪个字母 打印您希望使用哪封信? u_selected=输入> 筛选的单词=[如果选择了word.starts,则内容中的单词与单词对应
你能提供一个单词列表的例子吗?它基本上只是一个从a到Z的每个英语单词的列表。