Spaces:
Running
Running
File size: 2,990 Bytes
bdafe83 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
import json
import re
def is_json(myjson):
"""
Checks whether a given string is a valid JSON.
Parameters:
myjson (str): The string to be checked.
Returns:
bool: True if the string is a valid JSON, False otherwise.
"""
try:
_ = json.loads(myjson)
except ValueError:
return False
return True
def is_json_inside(text):
"""
Checks whether a given string contains valid JSON(s).
Parameters:
text (str): The string to be checked.
Returns:
bool: True if the string contains valid JSON(s), False otherwise.
"""
text = re.sub(r"\s+", " ", text)
matches = re.findall(r"\{.*?\}", text)
for match in matches:
if is_json(match):
return True
return False
def extract_jsons(text):
"""
Extracts all valid JSON objects from a given string.
Parameters:
text (str): The string from which JSON objects are to be extracted.
Returns:
List[Dict]: A list of all extracted JSON objects.
"""
text = re.sub(r"\s+", " ", text)
matches = re.findall(r"\{.*?\}", text)
parsed_jsons = []
for match in matches:
try:
json_object = json.loads(match)
parsed_jsons.append(json_object)
except ValueError:
pass
return parsed_jsons
def extract_code(text):
"""
Extracts all code blocks encapsulated by '```' from a given string.
Parameters:
text (str): The string from which Python code blocks are to be extracted.
Returns:
List[str]: A list of all extracted Python code blocks.
"""
text = re.sub("```python", "```", text)
matches = re.findall(r"```(.*?)```", text, re.DOTALL)
parsed_codes = []
for match in matches:
parsed_codes.append(match)
return parsed_codes
class AttributedDict(dict):
"""
A dictionary class whose keys are automatically set as attributes of the class.
The dictionary is serializable to JSON.
Inherits from:
dict: Built-in dictionary class in Python.
Note:
This class provides attribute-style access to dictionary keys, meaning you can use dot notation
(like `my_dict.my_key`) in addition to the traditional bracket notation (`my_dict['my_key']`).
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, key):
if key in self:
return self[key]
raise AttributeError
def __delattr__(self, key):
del self[key]
# check whether the key is string when adding the key
def __setitem__(self, key, value):
if not isinstance(key, str):
raise ValueError("The key must be a string")
super().__setitem__(key, value)
def update(self, *args, **kwargs):
for key, value in dict(*args, **kwargs).items():
self[key] = value
|