Python从电影类型中选择json的随机电影

时间:2018-04-30 00:50:42

标签: python json python-3.x random

import random
import json

# user_input = input('')

with open('robot.json') as f:
    data = json.load(f)

for film in data['films']:
    print(film["title"], film["category"])

在上面的代码中,我想添加一个用户输入,允许用户指定电影的类型并使用该响应,从“robot.json”文件中包含的相应类别中检索随机选择。

我似乎无法使用random.choice工作,但该程序将打印json中的所有条目。

我是新来的,所以我一直被困在杂草中。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

Random.choice“从非空序列中选择一个随机元素” 使用词典按类别分组电影应该会有所帮助。

import random
import json
from collections import defaultdict


with open('robot.json') as f:
    data = json.load(f)

d = defaultdict(list)                   
for film in data['films']:
    d[film["category"]].append(film)    # group films by category

user_input = input('')
if user_input in d:
    choice = random.choice(d[user_input])
    print(choice)
else:                                   # invalid input
    print('Unknown Category')

使用此示例文件

{
  "films": [
    { "title": "A", "category": "comedy" },
    { "title": "B", "category": "comedy" }
  ]
}

该脚本的工作方式与comedy ==> A or B, horror ==> Unknown Category

类似

答案 1 :(得分:0)

from bs4 import BeautifulSoup
import random
import requests
import webbrowser

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'Cache-Control': 'max-age=0',
}

response = requests.get('https://www.imdb.com/chart/top', headers=headers)
soup=BeautifulSoup(response.text, 'html.parser')
tbody=soup.find_all('td',class_='titleColumn')
######
######
while True:
    randomNmber=random.randint(0,len(tbody))
    nameOfMovie=tbody[randomNmber].find('a').text
    year=tbody[randomNmber].find('span').text
    link='https://www.imdb.com'+tbody[randomNmber].find('a').get('href')
    reso=requests.get(link,headers=headers)
    soupmv=BeautifulSoup(reso.text, 'html.parser')
    trailer=soupmv.find('a',class_='slate_button prevent-ad-overlay video-modal').get('href')
    trailerLINK='https://www.imdb.com'+trailer
    print('how about: '+nameOfMovie+' '+year) print('trailer link: '+trailerLINK) wht=input('go to trailer hit "go" new one hit "enter" exit(any key)') if wht=='go' or wht=='A': webbrowser.open(trailerLINK) if wht == '': continue else: break

访问https://www.icodes.tech/2021/02/pick-random-movie-with-a-script-python.html