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

最佳答案

您遇到的问题是拆分但未保存拆分行:

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


所以:

wordList.extend(line.split())


应该为你做把戏

关于python - 子手:文件I/O字符串并列出python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13312399/

10-10 22:20