how to get a list of key value from the markdown snippets that contain a document with for each the name of the snippet key (python, javascript, anything, and a number if more then one) so to have a dictionnary like {"java":"class somethin();","python1":"def somethin():",javascript1:"function somethin(){}","javascript2":"somethindifferent(){}"}
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a Python solution to extract code snippets from markdown and create a dictionary with language keys:
python
import re
from collections import defaultdict
def extract_code_snippets(markdown_text):
# Pattern to match code blocks with optional language identifier
pattern = r'```(\w*)\n(.*?)```'
# Find all matches
matches = re.findall(pattern, markdown_text, re.DOTALL)
# Track count of each language
language_counts = defaultdict(int)
result = {}
for language, code in matches:
# Default to 'code' if no language specified
if not language:
language = 'code'
# Track how many times we've seen this language
language_counts[language] += 1
# Create key with number if more than one
if language_counts[language] == 1:
key = language
else:
key = f"{language}{language_counts[language]}"
# Strip leading/trailing whitespace from code
result[key] = code.strip()
return result
# Example usage
markdown = """
# My Document
Here's some Python code:
```python
def something():
return "Hello"