【问题标题】:Python Select random film from json by film typePython按电影类型从json中选择随机电影
【发布时间】:2018-04-30 00:50:41
【问题描述】:
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 中的所有条目。

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

【问题讨论】:

    标签: python json python-3.x random


    【解决方案1】:

    Random.choice "从非空序列中随机选择一个元素".
    使用 dict 按类别对电影进行分组应该会有所帮助。

    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一样工作

    【讨论】:

    • 所以,当我将它输入到用户输入中时,我得到了一个 NameError: name 'comedy' is not defined。所以随机排序需要通过访问JSON中的“类别”标签来实现,然后它需要返回一个标题。如果这很明显,我深表歉意,但我也在努力解决这个问题。感谢您的反馈,如果您有其他想法,请告诉我。谢谢!
    • @Swan 抱歉,我不知道comedy 的来源。 else 声明应该保护未知类别。 NameError 发生在变量名不存在时。也许你可以告诉我是哪一行出现了错误?
    • python .\robot_test.py comedy Traceback(最近一次调用最后):文件“.\robot_test.py”,第 13 行,在 user_input = input('') File "",第 1 行,在 NameError: name 'comedy' is not defined
    • @Swan 看起来像您正在使用的 Python2。请使用raw_input,因为input 将输入评估为代码,然后没有名为comedy 的变量。或者切换到 Python3,input 可以根据需要工作。
    • 有效!我尝试了两种选择!谢谢!你知道我如何通过 HTML 容器路由它吗?
    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多