Last active
October 8, 2022 03:44
-
-
Save jskherman/9b2242282e7eb3b2545f57026bcbcc4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
text = "[hello:: world]\n[key:: value]\n[testing::1]\n[listing::1,2,3]" | |
# Caveat: These regex only work with one field on a line | |
# and cannot have two or more in the same line. | |
key_regex = r"(?!\[).*(?:(?=\:\:))" | |
value_regex = r"(?:(?<=\:\:)(.*)(?=\]))" | |
# Save values to a list | |
vals = re.findall(value_regex, text) | |
values = [] | |
for val in vals: | |
if re.search(r",", val): | |
val = [v.strip() for v in (val.split(","))] | |
values.append(val) | |
else: | |
values.append(val.strip()) | |
# Save keys to a list | |
fkeys = re.findall(key_regex, text) | |
keys = [] | |
for k in fkeys: | |
keys.append(k.strip()) | |
# Create dictionary that matches the keys to its values | |
fields = dict(zip(keys, values)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment