来自HTML文件的数据的计数器

2024-06-05 19:02:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个任务,我们使用正则表达式从HTML中列出10件事情

我设法从一个网站上列出了10件东西,但在tkinter上显示时,我需要它们旁边的数字

例如,1到10和/或10到1如下所示: 示例:
example

我知道我需要使用for循环,但我不知道如何使用,并且已经研究了很长一段时间

以下是我的一个窗口的代码:

def hidden_gems_on_disney_window():
    hidden_gems_on_disney = Tk()
    hidden_gems_on_disney['bg'] = 'pink'
    hidden_gems_on_disney.title('10 Hidden Gems On Disney+')
    hidden_gems_on_disney.geometry('500x500')
    Label(hidden_gems_on_disney, text = '10 Hidden Gems On Disney+ You Totally Missed', bg = 'SeaGreen2', font = ('Calibri', 15)).place(x=50, y=45)
    url = 'https://screenrant.com/disney-plus-hidden-gems/'
    web_page = urlopen(url)
    web_page_contents = web_page.read().decode('UTF-8')
#the pattern that I found to list my top 10.
    regex = r'(?<=</span>)(.*)(?=</h2>)'
#-------------------------------------------
    disney_plus = re.findall(regex, web_page_contents)
    x_coord = 40
    y_coord = 90
#This for loop shows top 10 contents on this website. There are already just 10 names, so in this case, it is not neccasery to use counter.
    for hidden_gems in disney_plus:
        Label(hidden_gems_on_disney, text = hidden_gems, bg ='pink', font = ('Malgun', 10)).place(x= x_coord, y= y_coord)
        y_coord = y_coord + 38
#Label for the hyperlink. Once clicked, it opens a browser and shows the webpage where data comes from.
    most_popular_songs_link = Label(hidden_gems_on_disney, text = 'https://screenrant.com/disney-plus-hidden-gems/', fg='dark green')
    most_popular_songs_link.place(x = 110, y = 475)
    most_popular_songs_link.bind('<Button-1>', lambda e: callback(url))
    
    mainloop()

这是此窗口的输出。:/br/>This is the output for this window.

由于这个网站排名10到1,我想显示10到1之间的数字,但如果有任何不同,我也想看看如何处理1到10之间的数字


Tags: textgemsweburlforonpageplace
2条回答

在循环中添加一个计数器


#This for loop shows top 10 contents on this website. There are already just 10 names, so in this case, it is not neccasery to use counter.
    counter=10;
    for hidden_gems in disney_plus:
        Label(hidden_gems_on_disney, text = str(counter) + ". " + hidden_gems, bg ='pink', font = ('Malgun', 10)).place(x= x_coord, y= y_coord)
        y_coord = y_coord + 38
        counter = counter -1

如果要增加计数器,请使用counter=1初始化,并使用counter = counter +1递增

您可以在for循环中使用enumerate()函数:

font = ('Malgun', 10)
for i, hidden_gems in enumerate(disney_plus[::-1], 1):  # in reverse order
    Label(hidden_gems_on_disney, text='{})'.format(i), bg='pink', font=font).place(x=x_coord, y=y_coord)
    Label(hidden_gems_on_disney, text=hidden_gems, bg='pink', font=font).place(x=x_coord+25, y=y_coord)
    y_coord += 38

相关问题 更多 >