How to return a list of words from a text file in python

10,834

Solution 1

If you used return in the loop, it returned on the first iteration and you only got back the first word.

What you want is an aggregation of the words - or better yet, return the array you got back from splitting the words. You may want to sanitize line breaks.

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()

To get a dictionary back, you can use this (takes care of line breaks):

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

To get key,value items back, you can use something like this to return a generator (keep in mind the file will be left open as long as the generator remains open). You can modify it to return just words if that's what you want, it's pretty straightforward:

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())

Example output for the first function:

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']

Solution 2

How about this:

def get_dictionary_word_list(fname):
    with open(fname) as fh:
        return set(fh.read().split())
Share:
10,834
alfiej12
Author by

alfiej12

Updated on June 13, 2022

Comments

  • alfiej12
    alfiej12 almost 2 years

    I want to return all words found in a text file. This is the code i have so far.

    def get_dictionary_word_list():
        f = open('dictionary.txt')
        for word in f.read().split():
            print(word)
    

    It works using the print fucntion but instead of printing the words i want to return all the words in the text file. Using return it only shows 'aa' and not the words in the file. Im not sure why it's not working with return?