我有一个文本文件要重新构造。该文件包含功能、功能描述(选项卡delim,描述符的数量会有所不同)以及显示该功能的人员列表。它看起来像这样:
Feature1 detail1 detail2
Person1
Person2
Feature2 detail1 detail2 detail3
Person3
我只想对它进行重组,使每行有一个特征,在描述符后面的行上加上人物,这样它就会看起来像这样:
Feature1 detail1 detail2 Person1 Person2
Feature2 detail1 detail2 detail3 Person3
我想用一本Python字典。我的代码将读取每个Feature作为键,并将详细信息作为值附加,但我在添加Persons作为值时遇到了问题。有人能帮忙吗?
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)
编辑:修复代码缩进
我只更改了if ... else
部分:
def reformat(filename):
mydict = dict()
feature = ''
for line in filename:
m = re.search("AFeature",line[0])
if m:
feature = line[0]
mydict[feature] = (line[1:-1])
else:
mydict[feature].append(line[0])
print(mydict)