Learn R Programming

llmflow (version 3.0.2)

extract_python_code: Extract Python code from a string

Description

This function extracts Python code from a string by matching all content between '```python', '```py' and '```'.

Usage

extract_python_code(input_string)

Value

A character vector containing the extracted Python code

Arguments

input_string

A string containing Python code blocks, typically a response from an LLM

Examples

Run this code
# Simple example
text <- "Python code:\n```python\nprint('Hello World')\n```"
extract_python_code(text)

# Using 'py' tag
text <- "```py\nimport numpy as np\n```"
extract_python_code(text)

# Multiple blocks with different tags
response <- "
Data processing:
```python
import pandas as pd
df = pd.read_csv('data.csv')
df.head()
```

Visualization:
```py
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
```
"
codes <- extract_python_code(response)
length(codes) # Returns 2

# Complex example with classes and functions
llm_response <- "
Here's a complete Python solution:
```python
class DataProcessor:
    def __init__(self, data):
        self.data = data

    def process(self):
        return [x * 2 for x in self.data]

processor = DataProcessor([1, 2, 3])
result = processor.process()
print(result)
```
"
extract_python_code(llm_response)

Run the code above in your browser using DataLab