我有以下问题。在我的初级Python课程中,期中考试就要到了,虽然我理解了练习期中的其他问题,但这一次让我有点难堪。首先,这是问题的文本。我遇到的麻烦是如何遍历一行中的每个单词,并检查它是否已经被看到。我觉得很难概念化。首先,以下是问题的文本:
Write a function named cloneLines that takes two parameters:
1. inFile, a string, the name of an input file that exists before cloneLines is called
2. outFile, a string, the name of an output file that cloneLines creates and writes to
函数cloneLines
逐行读取inFile
的内容,并将至少包含一个在该行中出现多次的单词的任何行写入outFile
。您可以假设输入文件只包含小写字母、空格和换行符。你知道吗
例如,如果以下是文件william.txt
的内容:
double double toil and trouble
fire burn and caldron bubble
eye of newt and toe of frog
fillet of a fenny snake
in the caldron boil and bake
double double toil and trouble
fire burn and caldron bubble
以下函数调用:
inFile = 'william.txt'
outFile = 'clones.txt'
cloneLines(inFile, outFile)
应创建包含以下内容的文件clones.txt
:
double double toil and trouble
eye of newt and toe of frog
double double toil and trouble
我只需要打开文件进行读写,然后开始for循环。再说一次,我很难理解这个。任何额外阅读的建议都会非常有用。我应该把从文件中读入的行分开吗?我只需要被指向一个大致的方向。你知道吗
def cloneLines (inFile, outFile):
inputfile = open(infile)
outputfile = open(outfile, 'w')
for line in inputfile.read():
...
以下内容将写入输出文件,即在该行中多次包含同一单词的任何行。你知道吗
相关问题 更多 >
编程相关推荐