返回dictionary.txt中的单词列表

时间:2017-11-16 23:08:04

标签: python list function file

我是Python的初学者。我乞求学习功能和文件。我需要编写一个代码,它将使用函数返回dictionary.txt中所有单词的列表,但我似乎无法弄明白。

当前代码

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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