如何使用 ".title() 命令读取文本文件并将文件中的每个单词大写?

How can I use the ".title() command to read a text file and capitalize every word in the file?

我的程序必须创建另一个名为 "CTL.py" 的文件,文本文件中的每个单词都大写,每个句子都以“#”结尾。我必须使用标题()。我的文本文件中有 131 行。我的思考过程是使用循环读取文本中的每个字母并将其大写,以及如何在 readline() 命令后添加“#”。关于如何解决这个问题有什么想法吗?

def main():

    myFile = open('/Users/Chandlers_Mac/Downloads/Lab9-2.txt', 'r')
    for i in range(131):
        data = myFile.read()
        data.title()
        print(data, end = '')

#end main   
main()

逐行迭代,标题,去除换行然后添加一个#,换行回来并将该行写入新文件:

with open('/Users/Chandlers_Mac/Downloads/Lab9-2.txt') as f,open("CTL.py", "w") as out:
    for line in f:
        out.write(line.title().rstrip()+"#\n")

关于您自己的代码:

data.title()

什么都不做,因为你不重新分配数据,你需要 data = data.title(),调用 title 创建一个新字符串,它不会修改原始字符串,你也不需要范围,即使你在之后做了对 .read() 迭代器的第一次调用将耗尽,因此接下来的 130 次调用将什么都不做。有很多更好的方法,但是如果您确实想使用该方法从文件中获取 131 行,您可以调用 next(myFile)myFile.readline() not read 因为它会一次读取整个文件。