Если вы использовали возврат в цикле, он возвращался на первую итерацию, и вы только вернули первое слово.
Что вы хотите, это агрегирование слов - или еще лучше, вернуть массив, который вы получили от разделения слов. Вы можете очистить разрывы строк.
def get_dictionary_word_list():
# with context manager assures us the
# file will be closed when leaving the scope
with open('dictionary.txt') as f:
# return the split results, which is all the words in the file.
return f.read().split()
Чтобы получить словарь обратно, вы можете использовать это (берет на себя разрывы строк):
def get_dictionary_word_list():
# with context manager assures us the
# file will be closed when leaving the scope
with open('dictionary.txt') as f:
# create a dictionary object to return
result = dict()
for line in f.read().splitlines():
# split the line to a key - value.
k, v = line.split()
# add the key - value to the dictionary object
result[k] = v
return result
Чтобы получить ключ, ценность предметов обратно, вы можете использовать что-то вроде этого, чтобы вернуть generator (имейте в виду, что файл остается открытым, пока генератор остается открытым). Вы можете изменить его, чтобы вернуть только слова, если это то, что вы хотите, это довольно просто:
def get_dictionary_word_list():
# with context manager assures us the
# file will be closed when leaving the scope
with open('dictionary.txt') as f:
for line in f.read().splitlines():
# yield a tuple (key, value)
yield tuple(line.split())
Пример вывода для первой функции:
xxxx:~$ cat dictionary.txt
a asd
b bsd
c csd
xxxx:~$ cat ld.py
#!/usr/bin/env python
def get_dictionary_word_list():
# with context manager assures us the
# file will be closed when leaving the scope
with open('dictionary.txt') as f:
# return the split results, which is all the words in the file.
return f.read().split()
print get_dictionary_word_list()
xxxx:~$ ./ld.py
['a', 'asd', 'b', 'bsd', 'c', 'csd']
вы хотите, чтобы все 2 выбора слов из файла? – Kasramvd