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.
To extract code snippets from a Markdown document and organize them into a dictionary with keys indicating the language and an optional index (if there are multiple snippets in the same language), you can use Python with the re module for regular expressions.
✅ Goal:
Given a Markdown string like this:
markdown
Some text here
```python
def something():
pass
More text...
javascript
function something() {}
Another example...
javascript
somethingDifferent();
And another Python snippet:
python
def another_function():
pass
Java example:
java
class SomeClass {}
code
You want to parse it and get a dictionary like:
```python
{
"python1": "def something():\n pass",
"javascript1": "function something() {}",
"javascript2": "somethingDifferent();",
"python2": "def another_function():\n pass",
"java1": "class SomeClass {}"
}
✅ Solution: Python Code
Here's a Python script that does exactly that:
python
import re
def extract_code_snippets(markdown_text):
# Pattern to match markdown code blocks
pattern = r'```(\w+)\s*\n(.*?)```'
matches = re.findall(pattern, markdown_text, re.DOTALL)
counts = {}
result = {}
for lang, code in matches:
lang = lang.lower()
counts[lang] = counts.get(lang, 0) + 1
key = f"{lang}{counts[lang]}"
# Strip trailing newlines and whitespace
result[key] = code.strip()
return result
# Example usage
markdown = """
Some text here
```python
def something():
pass
More text...
javascript
function something() {}
Another example...
javascript
somethingDifferent();
And another Python snippet:
python
def another_function():
pass
Java example:
java
class SomeClass {}
"""
snippets = extract_code_snippets(markdown)
for key, value in snippets.items():
print(f"{key}:\n{value}\n")
code
---
### 🧠 Explanation:
- **Regex**: `r'```(\w+)\s*\n(.*?)```'`
- `(\w+)`: captures the language name.
- `\s*\n`: skips any whitespace before the newline.
- `(.*?)`: non-greedy capture of the code content.
- **`re.DOTALL`**: allows `.` to match newlines.
- We count how many times each language appears to create unique keys like `"python1"`, `"javascript2"`, etc.
---
### ✅ Output:
```python
{
'python1': 'def something():\n pass',
'javascript1': 'function something() {}',
'javascript2': 'somethingDifferent();',
'python2': 'def another_function():\n pass',
'java1': 'class SomeClass {}'
}
Let me know if you'd like to write the output to JSON or include line numbers, etc.