Reversibility #99
-
If I use this to parse text into structured data, how hard would it be to come up with the reverse direction? Imagine a configuration file like:
should become something like {"parent": {"child": {"bad-parameter": True}, "other-child": {"bad-parameter": True}}} which then is fixed to {"parent": {"child": {"bad-parameter": False, "good-parameter": True}, "other-child": {"bad-parameter": False}}} which should result in
The whitespace in this scenario is syntax-relevant but should follow easy patterns. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
In general, deparsing is much easier than parsing. You don't typically need a library to deparse a data structure, just def convert_to_text_file(data, indent=0):
output = ""
for key, value in data.items():
if isinstance(value, dict):
output += " " * indent + key + "\n" + convert_to_text_file(value, indent + 4)
elif value:
output += " " * indent + key + "\n"
return output
data = {"parent": {"child": {"bad-parameter": False, "good-parameter": True}, "other-child": {"bad-parameter": False}}}
text_file_output = convert_to_text_file(data)
print(text_file_output + "!") The best way to deparse is dependent on the data structure, but some kind of recursive function is usually needed (like above). For those who stumble upon this question who have a proper AST, the |
Beta Was this translation helpful? Give feedback.
In general, deparsing is much easier than parsing. You don't typically need a library to deparse a data structure, just
str
. For example, a few rounds with ChatGPT and some manual tweaking gave me this to convert your data to the desired text: