如果你在循环中使用了 return,它会在第一次迭代时返回,你只得到第一个单词。
您想要的是单词的聚合 - 或者更好的是,返回从拆分单词中返回的数组。您可能需要清理换行符。
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']