给出这样的文本:
"$key\n
some value\n
$another_key\n
another longer\n
value\n"
# continue this trend with keys on lines marked by special symbol in this case $
# with corresponding value on the following lines until we hit another key
将其转换成这样的列表的好又简洁的方法
keys = ["$key", "$another_key"]
values = ["some value", "another longervalue"]
s = """$key\n
some value\n
$another_key\n
another longer\n
value\n"""
s = s.split("\n")[:-1] # we know the string ednwith \n
keys, values = [], []
for i in s:
if i[0] == "$" and i[1] !="$":
keys.append(i)
else:
values.append(i)
text = "$key\nsome value\n$another_key\nanother longer\nvalue"
key = []
value = []
for i in text.split('\n'):
if i[0]=='$':
key.append(i)
else:
value.append(i)
text = """$key # \n is implicit here
some value
$another_key
another longer"""
"""if you indeed had "\n" at the end as well then the next split would need
to be text.split("\n\n")"""
all_values = text.split('\n') # ["$key", "some value", "$another_key", "another longer"]
keys = []
values = []
new_dict = {}
for i in range(0, len(all_values), 2): # loop over list in steps of 2
key = all_values[i]
value = all_values[i + 1] # get the value to the right of your key
keys.append(key)
values.append(value)
new_dict[key] = value # could also store as a dict
print(keys)
>> ["$key", "$another_key"]
print(values)
>> ["some value", "another longer"]
print(new_dict)
>> {"$key": "some value", "$another_key": "another longer"}
尝试一下(假设text
是其中包含文本值的变量):
all_text = text.split('\n')
val_tup = [ (val, values[i+1]) for i,val in enumerate(values) if val.startswith('$') ]
keys, values = [ val[0] for val in val_tup ], [ val[1] for val in val_tup ]
您可以在行的开头使用$来标识这是一个新键,将其附加到键列表中,并将新的空白字符串附加到值列表中。然后,每当您有一行不以$开头的行时,您便会将值连接到value的最后一个元素,因为该行必须与当前键相关。仅当您阅读新键时,才创建新的空白值元素。
data = "$key\nsome value\n$another_key\nanother longer\nvalue\n"
keys = []
values = []
for line in data.split('\n'):
if line.startswith('$'):
keys.append(line)
values.append("")
else:
values[-1] += line
print(keys, values)
输出
['$key', '$another_key'] ['some value', 'another longervalue']