如何从非格式化CSV提取指定内容并在网页优雅展示?
Got it, let's work through this problem step by step. Your CSV has a non-standard structure where each row pairs an ID with a string that looks like a Python list of tuples—displaying the raw row text on a webpage is definitely messy. Here's how to extract the data cleanly and make it look good in the browser:
Step 1: Parse the Non-Standard CSV
First, we need to convert that messy string data into actual, usable Python objects. The ast.literal_eval() function is perfect here (it's safer than raw eval() for parsing structured strings).
import csv import ast # Load and parse the CSV processed_data = [] with open('some.csv', 'r') as csv_file: # Use csv.reader to handle quoted fields correctly reader = csv.reader(csv_file, quotechar='"', delimiter=',') for row in reader: # Clean up the ID and convert the score string to a list of tuples item_id = row[0].strip('"') score_list = ast.literal_eval(row[1].strip('"')) processed_data.append({ 'item_id': item_id, 'scores': score_list })
Step 2: Extract Your Target Content
Now you can filter or slice the data to get exactly what you need. For example:
- Grab only the top 5 highest scores per item
- Filter entries where the score is above a threshold (like 4.8)
- Extract just the entry IDs for each item
Here's an example of filtering for scores ≥4.8:
# Filter to keep only high-scoring entries filtered_data = [] for item in processed_data: high_scores = [entry for entry in item['scores'] if entry[1] >= 4.8] filtered_data.append({ 'item_id': item['item_id'], 'high_scores': high_scores })
Step 3: Optimize Web Display
Instead of dumping raw text, use structured HTML to make the data readable. Below are two clean options:
Option 1: Responsive Table
Tables are great for comparing values side-by-side:
<table style="width: 100%; border-collapse: collapse; margin: 20px 0;"> <thead> <tr> <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Item ID</th> <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Entry ID</th> <th style="border: 1px solid #ddd; padding: 8px; text-align: left;">Score</th> </tr> </thead> <tbody> {% for item in filtered_data %} {% for entry in item['high_scores'] %} <tr> <td style="border: 1px solid #ddd; padding: 8px;">{{ item['item_id'] }}</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ entry[0] }}</td> <td style="border: 1px solid #ddd; padding: 8px;">{{ "{:.2f}".format(entry[1]) }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table>
(Note: This uses Jinja2 template syntax—if you're not using a framework like Flask/Django, you can generate the HTML string directly in Python by looping through the data and concatenating tags.)
Option 2: Collapsible Sections
If you have lots of entries per item, collapsible panels keep the page uncluttered:
<div style="margin: 10px 0;"> {% for item in processed_data %} <details style="border: 1px solid #ddd; padding: 10px; margin-bottom: 5px;"> <summary style="font-weight: bold; cursor: pointer;">Item {{ item['item_id'] }} ({{ len(item['scores']) }} entries)</summary> <ul style="list-style-type: none; padding-left: 20px; margin-top: 10px;"> {% for entry in item['scores'] %} <li>Entry {{ entry[0] }}: <strong>{{ "{:.2f}".format(entry[1]) }}</strong></li> {% endfor %} </ul> </details> {% endfor %} </div>
Quick Tips for Polish
- Format scores to 2-3 decimal places to avoid messy long numbers
- Add subtle CSS (like hover effects on table rows) to improve interactivity
- If you're working with a large dataset, add pagination or search functionality to help users navigate
内容的提问来源于stack exchange,提问作者ajsingadiya

