如何获得前 6 个文本

How to get the first 6 texts

现在我有一个包含许多评级的输出,并且只想打印出 python 中的前六名。

import re
import requests

data = requests.get('https://www.imdb.com/chart/').text
titles = re.findall('/title/\w*/(?=">)', data)
rating = re.findall('\d\.\d.*ratings', data) 

rating

我得到的输出:

['8.8 based on 716,954 user ratings',
 '8.8 based on 1,729,095 user ratings',
 '8.8 based on 1,937,913 user ratings',
 '8.7 based on 1,902,393 user ratings',
 '8.7 based on 2,167,514 user ratings',
 '8.7 based on 1,544,013 user ratings',
 '8.7 based on 1,203,819 user ratings',
 '8.6 based on 1,753,684 user ratings',

您可以通过以下方式获取列表中的前六项:

your_list[:6]

EDIt

for i in range(0,len(user_ratings)):
   user_ratings[i] = f"No {i+1}: {user_ratings[i]}" 
user_ratings[:6]

user_ratings = [f"No {i+1}: {user_ratings[i]}" for i in range(0, len(user_ratings))]

user_ratings[0:6] 将打印出列表中的前六个元素 user_ratings

我假设你真的想获得 user_ratings 的前六个元素。
您可以使用列表切片来做同样的事情。此外,您可以使用列表理解和 f-strings 在评分前添加文本:

initial_six = user_ratings[:6]

formatted_text = [f'No.{initial_six.index(i)+1}: {i}' for i in initial_six]
print(formatted_text)

试试这个!以下代码将解决您的问题:

import re
import requests, pprint

data = requests.get('https://www.imdb.com/chart/top').text
titles = re.findall('/title/\w*/(?=">)', data)
rating = re.findall('\d\.\d.*ratings', data)

rating_arr = []
for rate in rating[0:6]:
    rating_arr.append("No. {}: ".format(rating[0:6].index(rate) + 1) + rate)

pprint.pprint(rating_arr)

输出如下:

['No. 1: 9.2 based on 2,460,844 user ratings',
 'No. 2: 9.1 based on 1,702,157 user ratings',
 'No. 3: 9.0 based on 1,182,290 user ratings',
 'No. 4: 9.0 based on 2,416,183 user ratings',
 'No. 5: 8.9 based on 728,548 user ratings',
 'No. 6: 8.9 based on 1,265,055 user ratings']