2

Writing a hangman program in python and I've come across a problem when passing in a file that has multi word strings and single word strings.

FILE:

hello brown fox

dog

cat

water

jump

#initialize list
wordList = []
# get and open file
getFile = raw_input("Enter file name: ")
filename = open(getFile, "r")

def readWords(filename):
    for line in filename:
        # split any multi word line
        line.split()
        # add line to wordList
        wordList.append(line)

Yet the out put for wordList still reads:

wordList = ['hello brown fox\n', 'dog\n', 'cat\n', 'water\n', 'jump\n']

I am trying to make it so that 'hello brown fox' appears as 3 separate strings.

3 Answers 3

1

You are making this too complicated - just .split the entire file contents:

with open(getFile, "r") as f:
    words = f.read().split()
0

the problem you're having is that you're splitting but not saving the splitted line:

>>> a = "hello brown fox"
>>> a.split()
['hello', 'brown', 'fox']
>>> a
'hello brown fox'
>>> 

so:

wordList.extend(line.split())

should do the trick for you

1
  • 1
    Ahh thank you! I tried appending line.split() before but that gave me a list of lists, I can't believe I forgot about extend. Nov 9, 2012 at 17:06
0

The split function returns the result as a list, so appending it directly would probably not what you desire. You can try the following example:

def main():
    l_wordList = ['hello brown fox\n', 'dog\n', 'cat\n', 'water\n', 'jump\n']
    l_words_list = []
    l_word = ''
    for word in l_wordList:
        if isinstance(word.split(), list):
            for token in word.split():
                l_words_list.append(token)
        else:
            l_words_list.append(word)

    for word in l_words_list:
        print(word)

main()

And the result will be this

>>>
hello
brown
fox
dog
cat
water
jump
>>>

Regards,

Dariyoosh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.