首页 > 解决方案 > Python `print` 函数中的 end='\r' 并不总是有效

问题描述

我编写了一个简单的函数来处理链接列表并从中获取有用的信息。在函数内部,我想要一个print函数来告诉我它现在正在处理哪个元素。但在这种情况下,输出不是我所期望的。这是我的清单和我的代码。

list = ['https://www.theguardian.com/world/2020/nov/18/test-and-trace',
 'https://www.theguardian.com/world/2000/jan/27/3',
 'https://www.theguardian.com/world/2020/nov/14/israeli-agents-in-iran-kill',
 'https://www.theguardian.com/world/2020/nov/10/nagorno-karabakh-peace-deal',
 'https://www.theguardian.com/world/2020/dec/06/professor-neil-ferguson',
 'https://www.theguardian.com/world/2020/nov/15/south-australia-records-three',
 'https://www.theguardian.com/world/2000/feb/28/gender.uk2']

和我的代码:

def tidy_links(links):
    # make an empty dataframe for putting all links in a tidy manner
    df = pd.DataFrame(columns=['cat', 'year', 'month', 'day', 'url', 'name'])

    # loop over links
    for i in range(len(links)):
        print('Processing link number ', i, 'out of', len(links), end = '\r')

        # add the data to the dataframe
        s = links[i].split('/')
        name = s[-5] + '_' + s[-4] + '_' + s[-3] + '_' + s[-2] + '_' + s[-1]
        df.loc[len(df)] = [s[-5], s[-4], s[-3], s[-2], links[i], name]
    return df

这是输出:

df = tidy_links(links)
Processing link number  3060 out of 3061 0108 out of 3061 0238 out of 3061 0494 out of 3061 0802 out of 3061 1186 out of 3061 2265 out of 3061

标签: python

解决方案


我相信这就是你所追求的

def tidy_links(links):
    # make an empty dataframe for putting all links in a tidy manner
    df = pd.DataFrame(columns=['cat', 'year', 'month', 'day', 'url', 'name'])

    # loop over links
    for i in range(len(links)):
        print('Processing link number %d out of %d \r' % (i, len(links)), end = '\r')

        # add the data to the dataframe
        s = links[i].split('/')
        name = s[-5] + '_' + s[-4] + '_' + s[-3] + '_' + s[-2] + '_' + s[-1]
        df.loc[len(df)] = [s[-5], s[-4], s[-3], s[-2], links[i], name]
    return df

来源:

如何在控制台上的同一位置写入输出?


推荐阅读