You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从HTML表单获取输入填充Python字典并展示算法结果

Got it, let's solve this problem by building a simple web interface using Flask—this will let you easily capture user inputs from HTML text boxes and pass them to your Python algorithm. Here's a step-by-step solution:

Step 1: Set Up Flask

First, install Flask if you haven't already:

pip install flask

Step 2: Create the Flask App

Create a file named app.py with the following code. This handles serving the input form and processing the submitted data:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def knapsack_input():
    if request.method == 'POST':
        try:
            # Capture basic inputs
            capacity = int(request.form['capacity'])
            num_of_items = int(request.form['num_of_items'])
            total_weight = int(request.form['total_weight'])
            total_value = int(request.form['total_value'])
            
            # Capture dynamic item weights and values
            item_weight = {}
            item_value = {}
            for i in range(num_of_items):
                item_weight[i] = int(request.form[f'item_weight_{i}'])
                item_value[i] = int(request.form[f'item_value_{i}'])
            
            # Here you can insert your knapsack algorithm code using these variables
            # For now, we'll just display the parsed inputs
            return render_template('result.html',
                                   capacity=capacity,
                                   num_of_items=num_of_items,
                                   total_weight=total_weight,
                                   total_value=total_value,
                                   item_weight=item_weight,
                                   item_value=item_value)
        
        except ValueError:
            return render_template('form.html', error="All inputs must be integers! Check your entries.")
        except KeyError:
            return render_template('form.html', error="Missing some item inputs—make sure all fields are filled.")
    
    # If it's a GET request, show the input form
    return render_template('form.html')

if __name__ == '__main__':
    app.run(debug=True)

Step 3: Create the Input Form

Make a folder named templates in the same directory as app.py, then create form.html inside it. This form uses JavaScript to generate dynamic fields for each item's weight and value:

<!DOCTYPE html>
<html>
<head>
    <title>Knapsack Problem Input</title>
    <script>
        // Generate item fields when user enters number of items
        function generateItemFields() {
            const numItems = document.getElementById('num_of_items').value;
            const container = document.getElementById('items_container');
            container.innerHTML = '';
            
            for (let i = 0; i < numItems; i++) {
                const itemDiv = document.createElement('div');
                itemDiv.innerHTML = `
                    <label>Item ${i}:</label>
                    <input type="number" name="item_weight_${i}" placeholder="Weight" required>
                    <input type="number" name="item_value_${i}" placeholder="Value" required><br><br>
                `;
                container.appendChild(itemDiv);
            }
        }
    </script>
</head>
<body>
    <h1>Knapsack Problem Input</h1>
    {% if error %}
        <p style="color: red;">{{ error }}</p>
    {% endif %}
    <form method="POST">
        <label for="capacity">Knapsack Capacity:</label>
        <input type="number" id="capacity" name="capacity" required><br><br>
        
        <label for="num_of_items">Number of Items:</label>
        <input type="number" id="num_of_items" name="num_of_items" min="1" required onchange="generateItemFields()"><br><br>
        
        <label for="total_weight">Total Weight (Input):</label>
        <input type="number" id="total_weight" name="total_weight" required><br><br>
        
        <label for="total_value">Total Value (Input):</label>
        <input type="number" id="total_value" name="total_value" required><br><br>
        
        <div id="items_container">
            <!-- Dynamic item fields will appear here -->
        </div>
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Step 4: Create the Result Page

Inside the templates folder, create result.html to display the parsed inputs (you can modify this to show your algorithm's output instead):

<!DOCTYPE html>
<html>
<head>
    <title>Input Parsed Successfully</title>
</head>
<body>
    <h1>Your Input Data</h1>
    <p><strong>Capacity:</strong> {{ capacity }}</p>
    <p><strong>Number of Items:</strong> {{ num_of_items }}</p>
    <p><strong>Total Weight:</strong> {{ total_weight }}</p>
    <p><strong>Total Value:</strong> {{ total_value }}</p>
    
    <h2>Item Weights:</h2>
    <ul>
        {% for item_id, weight in item_weight.items() %}
            <li>Item {{ item_id }}: {{ weight }}</li>
        {% endfor %}
    </ul>
    
    <h2>Item Values:</h2>
    <ul>
        {% for item_id, value in item_value.items() %}
            <li>Item {{ item_id }}: {{ value }}</li>
        {% endfor %}
    </ul>
    
    <a href="/">Go back to input form</a>
</body>
</html>

How to Use It

  1. Run app.py—you'll see a local server URL (usually http://localhost:5000).
  2. Open that URL in your browser.
  3. Enter the required values: when you type the number of items, dynamic fields for each item's weight and value will appear automatically.
  4. Submit the form, and you'll see your parsed inputs displayed (you can replace this part with your knapsack algorithm logic).

This approach replaces your hardcoded values with user inputs from HTML, and Flask handles all the server-side processing to convert those inputs into the variables and dictionaries your algorithm needs.

内容的提问来源于stack exchange,提问作者Sajal Roychowdhury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:19:55