2017-11-16 4 views
0

私はPythonの初心者です。関数とファイルについて学びたいと思っています。私は関数を使ってdictionary.txtのすべての単語のリストを返すコードを書く必要がありますが、私はそれを理解していないようです。dictionary.txtの単語リストに戻る

現在のコードあなたがリストを作成し、そこに単語を追加する必要が

def get_dictionary_wordlist(dic): 
    dic = open("dictionary.txt", "r") 
    for word in dic: 
     return word 
+0

あなたは、あなたの質問にdictionary.txtのフォーマットのサンプルを提供することができますか? – eugenhu

+0

すべての単語がスペースで区切られているだけであれば、dic.split()で 'for word 'を試すことができます:' – eugenhu

答えて

0

、あなたはそれを返します。

def get_dictionary_wordlist(dic): 
    words = [] # Make a list 
    dic = open("dictionary.txt", "r") 
    for word in dic: 
     words.append() # Add words to the list 
    return words 
0

これは動作するはずです:

dictionary = ('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'), ('USA', 'Hamburger') # Opening the dictionary 

def listWords(dic): # Creating the function 
    y = dict(dic) # Making sure dic is a dic 
    x = [] #creating the list 
    for key in dic: # Iterating through every item in dic 
     x.append(key) # Adding the item to the end 
    return x #returning the results 

print listWords(dictionary) #printing the results for the original text, dictionary 
+0

関数内で辞書を開くことができませんか? –

+0

でも、関数でそれを開くと、関数によって定義されたローカルの '(dic)'変数を冗長にすることができます。デフget_dictionary_wordlist(DIC): 言葉= [] オープン= DIC( "dictionary.txt"、 "R")の単語のための DICに: words.appendを –

+0

はIこれは私が持っているものである、あなたの方法を使用してみました(word) return words print(get_dictionary_wordlist(dic))#if私は機能しない関数の外で印刷し、関数内で印刷すると何も印刷されません。 –

関連する問題