如何随机化列表的内容

时间:2018-04-14 13:00:52

标签: python python-3.x list random

我正在尝试创建一个脚本,用于抓取网站中的短语,这些短语会保存到列表中,然后以随机方式显示。 这是代码 -

from bs4 import BeautifulSoup
import requests
import random

url = 'https://www.phrases.org.uk/meanings/phrases-and-sayings-list.html'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')

for phrase in soup.find_all(class_='phrase-list'):
    phrase_text = phrase.text
    print(phrase_text)

这会显示已删除的整个短语列表。 如何从所有短语列表中随机显示一个短语?

2 个答案:

答案 0 :(得分:0)

使用random.choice

from bs4 import BeautifulSoup
import requests
import random

url = 'https://www.phrases.org.uk/meanings/phrases-and-sayings-list.html'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')


lst = []
for phrase in soup.find_all(class_='phrase-list'):
    phrase_text = phrase.text
    lst.append(phrase_text)

random.choice(lst)

输出

'I have not slept one wink'

答案 1 :(得分:0)

最好将短语存储为列表,然后使用random.shuffle()

from bs4 import BeautifulSoup
import requests
import random

url = 'https://www.phrases.org.uk/meanings/phrases-and-sayings-list.html'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')

all_phrases = []

for phrase in soup.find_all(class_='phrase-list'):
    all_phrases.append(phrase.text)

random.shuffle(all_phrases)  # Replaces the list with a shuffled list

for phrase in all_phrases:
    print(phrase)