从http://localhost:8080/tester响应提取字符串并按键分组
Got it, let's break down how to extract the relevant strings from your service response and group those key-value pairs exactly how you need. Here's a step-by-step guide with code examples to make this concrete:
First, you need to retrieve the raw response text from your endpoint. Below are examples using Python (with requests) and curl:
Python Example
import requests # Fetch the response response = requests.get("http://localhost:8080/tester") response_text = response.text # Print to verify you're getting the expected content print(response_text)
Curl Example (Command Line)
curl http://localhost:8080/tester
Your response has two main key-value blocks: pri:{...} and sec:{...}. We'll use regular expressions to isolate these sections from the raw text.
Python Regex Extraction
import re # Match the content inside pri:{...} and sec:{...} pri_match = re.search(r'pri:\{(.*?)\}', response_text) sec_match = re.search(r'sec:\{(.*?)\}', response_text) # Extract the raw key-value strings (if matches exist) pri_kv_raw = pri_match.group(1) if pri_match else "" sec_kv_raw = sec_match.group(1) if sec_match else ""
JavaScript Regex Extraction
async function fetchResponse() { const response = await fetch('http://localhost:8080/tester'); const text = await response.text(); // Extract pri and sec blocks const priMatch = text.match(/pri:\{(.*?)\}/); const secMatch = text.match(/sec:\{(.*?)\}/); const priKvRaw = priMatch ? priMatch[1] : ""; const secKvRaw = secMatch ? secMatch[1] : ""; return { priKvRaw, secKvRaw }; }
Next, convert the extracted raw strings into structured key-value dictionaries so we can work with them easily.
Python Parsing Function
def parse_kv_string(kv_raw): # Split into individual key-value pairs kv_pairs = kv_raw.split(', ') parsed_dict = {} for pair in kv_pairs: if not pair: continue # Split each pair into key and value (convert to integers) key_str, value_str = pair.split('=') parsed_dict[int(key_str)] = int(value_str) return parsed_dict # Parse both pri and sec sections pri_dict = parse_kv_string(pri_kv_raw) sec_dict = parse_kv_string(sec_kv_raw)
JavaScript Parsing Function
function parseKvString(kvRaw) { const parsed = {}; if (!kvRaw) return parsed; kvRaw.split(', ').forEach(pair => { const [keyStr, valueStr] = pair.split('='); parsed[parseInt(keyStr)] = parseInt(valueStr); }); return parsed; } // Usage after fetching: const { priKvRaw, secKvRaw } = await fetchResponse(); const priDict = parseKvString(priKvRaw); const secDict = parseKvString(secKvRaw);
Now that we have structured dictionaries, we can group them based on your needs. Below are two common grouping scenarios:
Scenario 1: Group by Value (e.g., all keys that map to the same value)
Python Grouping by Value
from collections import defaultdict def group_by_value(kv_dict): grouped = defaultdict(list) for key, value in kv_dict.items(): grouped[value].append(key) # Convert defaultdict to regular dict for readability return dict(grouped) # Group pri and sec dictionaries by their values pri_grouped_by_value = group_by_value(pri_dict) sec_grouped_by_value = group_by_value(sec_dict) print("Pri grouped by value:", pri_grouped_by_value) print("Sec grouped by value:", sec_grouped_by_value)
JavaScript Grouping by Value
function groupByValue(kvDict) { const grouped = {}; Object.entries(kvDict).forEach(([key, value]) => { const numKey = parseInt(key); if (!grouped[value]) { grouped[value] = []; } grouped[value].push(numKey); }); return grouped; } const priGroupedByValue = groupByValue(priDict); const secGroupedByValue = groupByValue(secDict); console.log("Pri grouped by value:", priGroupedByValue);
Scenario 2: Group by Key Range (e.g., keys 0-9, 10-19, etc.)
Python Grouping by Key Range
def group_by_key_range(kv_dict, range_size=10): grouped = defaultdict(list) for key, value in kv_dict.items(): # Calculate the range label (e.g., 0-9 for key 5) range_start = (key // range_size) * range_size range_end = range_start + range_size - 1 range_label = f"{range_start}-{range_end}" grouped[range_label].append((key, value)) return dict(grouped) # Group pri dictionary into ranges of 10 pri_grouped_by_range = group_by_key_range(pri_dict) print("Pri grouped by key range:", pri_grouped_by_range)
内容的提问来源于stack exchange,提问作者flash

