如何对文件的python中的最后一个单词执行echo函数

时间:2015-04-17 05:30:37

标签: python string

详细问题是: 编写一个函数,它接受一个表示文件名的字符串作为参数和一个数字x。 打开文件并使用while循环构建并返回包含文件中短语的字符串 最后一个字x次。 注意新的行。

def echo(filename, x):
    """
    >>> echo("phrase.txt", 2)
    'Hello World!\\nWorld!\\nWorld!\\n'
    >>> echo("phrase.txt", 4)
    'Hello World!\\nWorld!\\nWorld!\\nWorld!\\nWorld!\\n'
    """

if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)
我试图做的是:

def echo(filename,x):
    files=open(filename,"r")
    text=files.read()
    filelist=text.split()
    last_word=filelist[len(filelist)-1]
    n=len(last_word)
    count=last_word
    while n<n*x:
        count=count+last_word
        n=n+1
    return count   

但不幸的是,这不会奏效。 作为一个仍然在蟒蛇中挣扎的新鱼,我真的需要有人帮我一把。

2 个答案:

答案 0 :(得分:0)

你非常接近。我将对您的代码进行微小的更改,在我做出更改的任何地方添加评论:

def echo(filename,x):
    files = open(filename,"r")
    text = files.read()
    filelist = text.split()
    last_word = filelist[len(filelist)-1]
    n = 1  # let's just count the number of times you add the last word
    count = text
    while n<x:
        count = count + last_word
        n = n + 1
    return count

答案 1 :(得分:0)

另一个回答者是不是很正确......这应该是怎么样:)

def echo(filename, x):
    files = open(filename,"r")
    text = files.read()
    filelist = text.split()
    last_word = text.rsplit(None, 1)[-1]
    files.close()
    n = 0
    string = text
    while n < x:
        string = string + "\n" + last_word
        n = n + 1
    return string + "\n"