Hangman:文件I / O字符串和列表python

时间:2012-11-09 16:51:15

标签: python

在python中编写一个hangman程序,我在传入一个包含多个单词字符串和单个单词字符串的文件时遇到了问题。

文件:

你好,棕色的狐狸

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

然而,wordList的输出仍然是:

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

我试图让'hello brown fox'显示为3个单独的字符串。

3 个答案:

答案 0 :(得分:1)

你这太复杂了 - 只需.split整个文件内容:

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

答案 1 :(得分:0)

你遇到的问题是你正在拆分而不是保存分割线:

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

这样:

wordList.extend(line.split())

应该为你做的伎俩

答案 2 :(得分:0)

split函数将结果作为列表返回,因此直接附加它可能不是您想要的。您可以尝试以下示例:

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

结果将是这个

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

此致

Dariyoosh