2017-01-09 6 views
0

私は既に.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. 

これは私が最初に考え何ですが、それは仕事をdidntの、私はどこで行くことを知らない...

+6

「機能しませんでした」は問題の説明が不十分です。あなたが持っている問題を説明してください。 See [ask]。 – khelwood

+1

'str'の' .startswith'メソッドを使用します – BloodyD

答えて

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)] 
+0

'word'は実際個々の文字です –

+0

うわー、私はそれをテストしなかった、私は仕事中です。編集されました。 – Will

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) 
関連する問題