python - 刽子手 : File I/O strings and lists python

标签 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 个独立的字符串。

最佳答案

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

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

关于python - 刽子手 : File I/O strings and lists python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13312399/

相关文章:

python - 使用 sklearn 计算 F1 分数

python - 我们如何获取长整数的用户输入?

python - 从打开的文件设置多个变量 - Python

python - 如何从文本文件获取数据并重写为另一个文件

c# - 在 C# 中解释这个 python 表达式

python - 将 float 转换为字符串,并在 Python 中的点后切割零位小数

python - 如何使用 python requests.head 方法跟踪 30x 重定向

Python将png文件发送到默认打印机

python - 永久更改变量

python - 有没有办法在 SymPy 中获得分步解决方案?