I have a text file that contains these lines and I’m not exactly sure what’s the best way to use Python to load into separate key:value pairs.
dummy-test-foo,rsa,4096,[DNS.1:dummy-test,DNS.2:dummy-test-foo2],[IP.1:192.168.10.5,IP.2:192.168.20.5]
dummy-test-jerry,rsa,4096,[DNS.1:dummy-testX,DNS.2:dummy-test-jerry],[IP.1:192.168.40.5,IP.2:192.168.50.5]
dummy-test-tom,rsa,4096,[DNS.1:dummy-testY,DNS.2:dummy-test-tom],[IP.1:192.168.60.5,IP.2:192.168.70.5]
The challenge is the embedded array within each line.
Novice Python programmer, not sure where to start.
2
Use the str.split()
function with the maxsplit
option to limit it to the first 3 commas. Then you can use a regular expression to extract the arrays from the rest.
import re
array_rx = re.compile(r'[(.*?)]')
with open("testarrays.txt") as f:
for line in f:
name, type, size, arrays = line.split(',', maxsplit=3)
# split the arrays string into separate elements, removing [] delimiters
arrays = array_rx.findall(arrays)
print(name, type, size, arrays)
Without a regexp
it can be done in the following way:
lines = [
"dummy-test-foo,rsa,4096,[DNS.1:dummy-test,DNS.2:dummy-test-foo2],[IP.1:192.168.10.5,IP.2:192.168.20.5]",
"dummy-test-jerry,rsa,4096,[DNS.1:dummy-testX,DNS.2:dummy-test-jerry],[IP.1:192.168.40.5,IP.2:192.168.50.5]",
"dummy-test-tom,rsa,4096,[DNS.1:dummy-testY,DNS.2:dummy-test-tom],[IP.1:192.168.60.5,IP.2:192.168.70.5]",
]
def parse_line(line: str) -> dict:
result: dict = {}
# Split by comma
line = line.split(",")
# Find all words containing colon
for word in line:
if ":" not in word:
continue
# Remove brackets and convert to key / value pair
word = "".join(char for char in word if char not in "[]")
key, value = word.split(":")
result[key] = value
return result
for line_ in lines:
parse_line(line=line_)
3