I have a text file that I would like to restructure. The file contains features, a description of the features(tab delim, the number of descriptors will vary), and a list of people displaying that feature. It looks like this:
Feature1 detail1 detail2
Person1
Person2
Feature2 detail1 detail2 detail3
Person3
…and I would just like to restructure it so that there is one feature per row, with the persons tacked onto the line after the descriptors so it would look like this:
Feature1 detail1 detail2 Person1 Person2
Feature2 detail1 detail2 detail3 Person3
I would like to use a Python dictionary. My code which will read each Feature as a key and append the details as values, but I am having trouble adding the Persons as values. Can anyone help?
import re
import sys
import csv
def reformat(filename):
mydict = dict()
for line in filename:
m = re.search("\AFeature",line[0])
if m:
if str(line) in mydict:
mydict[line].append(line[0])
else:
mydict[line[0]] = (line[1:-1])
print(mydict)
thefilename = "path"
path_reader=csv.reader(open(thefilename), delimiter = "\t")
rv = reformat(path_reader)
edit: fixed code indentation
I only changed the
if ... elsepart: