I have this following string in a text file
InfoType 0 :
string1
string2
string3
InfoType 1 :
string1
string2
string3
InfoType 3 :
string1
string2
string3
Is there a way to create a dictionary that would look like this:
{'InfoType 0':'string1,string2,string3', 'InfoType 1':'string1,string2,string3', 'InfoType 3':'string1,string2,string3'}
Something like this should work:
def my_parser(fh, key_pattern):
d = {}
for line in fh:
if line.startswith(key_pattern):
name = line.strip()
break
# This list will hold the lines
lines = []
# Now iterate to find the lines
for line in fh:
line = line.strip()
if not line:
continue
if line.startswith(key_pattern):
# When in this block we have reached
# the next record
# Add to the dict
d[name] = ",".join(lines)
# Reset the lines and save the
# name of the next record
lines = []
name = line
# skip to next line
continue
lines.append(line)
d[name] = ",".join(lines)
return d
Use like so:
with open("myfile.txt", "r") as fh:
d = my_parser(fh, "InfoType")
# {'InfoType 0 :': 'string1,string2,string3',
# 'InfoType 1 :': 'string1,string2,string3',
# 'InfoType 3 :': 'string1,string2,string3'}
There are limitations, such as:
You could get around these by making the function a generator
and yielding name, str
pairs and processing them as you read the file.
This will do:
dictionary = {}
# Replace ``file.txt`` with the path of your text file.
with open('file.txt', 'r') as file:
for line in file:
if not line.strip():
continue
if line.startswith('InfoType'):
key = line.rstrip('\n :')
dictionary[key] = ''
else:
value = line.strip('\n') + ','
dictionary[key] += value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.