查找以用户指定的字母开头的列表中的项目

时间:2017-01-09 13:54:51

标签: python

我试图创建一个程序,我已经有一个正在从.txt文件中读取的列表,现在我需要这样做,以便当我给Python我的“所需字母”时,它会把我所有的项目都放入将那封信写入另一个名单。

提前致谢

countrypopList = open("E:\\SCRIPTING\\Countries.txt").readlines() #This is     making "countrypopList" contain everthing on the txt.
countrypopList.sort() #This is sorting the list alphabetically.
useriList = []
countries = []
population = []
userI = input("Please input a single letter: ") #Ask user to input a single     letter.

if userI.isalpha():
    if len(userI) > 1:
        print("Please enter only a single letter.") #If user input length is     over 1, display this message.

    else: #If there are no complications and the user inputs a single letter     as required, the program continues.
        #print("continue")
        for line in countrypopList:
            if (line.startswith(userI)):
                useriList.append(line)

    print(useriList)            
else:
    print("Please make sure that you enter a single letter.") #If user     inputs anything other than a letter with a length of 1, display this message.

这是我一开始的想法,但它没有用,我不知道该去哪里..

2 个答案:

答案 0 :(得分:1)

您可以使用列表理解:

text = open('data.txt').read()
user_letter = raw_input('Please enter one letter: ')
starts_with = [word for word in text.split() if word.startswith(user_letter)]

答案 1 :(得分:1)

假设您已准备好文本列表,则可以使用您的用户输入和列表将其调用到此函数:

def startString(char, userlist):
    ls = []
    for string in userlist:
        if string.startswith(char):
            ls.append(string)
    print(ls)

startString(userI,yourList) #call fuction on your data(userinput and your list from text)