2

用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 个单独的字符串。

4

3 回答 3

1

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

with open(getFile, "r") as f:
    words = f.read().split()
于 2012-11-09T17:38:33.017 回答
0

您遇到的问题是您正在拆分但未保存拆分线:

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

所以:

wordList.extend(line.split())

应该为你解决问题

于 2012-11-09T17:00:00.897 回答
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
>>>

问候,

达里约什

于 2012-11-09T17:08:40.353 回答