【问题标题】:How to randomize contents of a list [duplicate]如何随机化列表的内容[重复]
【发布时间】:2018-04-14 13:00:52
【问题描述】:

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

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)

这会显示被抓取的整个短语列表。 如何从所有短语列表中随机显示一个短语?

【问题讨论】:

  • 如果您只想显示单个元素,请使用 random.choice,如果您想打乱整个列表,请使用 random.samplerandom.shuffle

标签: python python-3.x list random


【解决方案1】:

使用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'

【讨论】:

    【解决方案2】:

    您最好将短语存储为列表,然后使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2011-12-06
      • 2023-03-06
      • 2016-04-24
      • 2012-04-15
      相关资源
      最近更新 更多