Python:通过字典重新构造有序文本文件
我有一个文本文件,我想重组。该文件包含功能、功能描述(tab delim,描述符的数量会有所不同)以及显示该功能的人员列表。看起来是这样的:Python:通过字典重新构造有序文本文件,python,text,dictionary,key,Python,Text,Dictionary,Key,我有一个文本文件,我想重组。该文件包含功能、功能描述(tab delim,描述符的数量会有所不同)以及显示该功能的人员列表。看起来是这样的: Feature1 detail1 detail2 Person1 Person2 Feature2 detail1 detail2 detail3 Person3 Feature1 detail1 detail2 Person1 Person2 Feature2 detail1 det
Feature1 detail1 detail2
Person1
Person2
Feature2 detail1 detail2 detail3
Person3
Feature1 detail1 detail2 Person1 Person2
Feature2 detail1 detail2 detail3 Person3
…我只想对其进行重组,使每行有一个功能,在描述符后面的行上钉上人员,使其看起来像这样:
Feature1 detail1 detail2
Person1
Person2
Feature2 detail1 detail2 detail3
Person3
Feature1 detail1 detail2 Person1 Person2
Feature2 detail1 detail2 detail3 Person3
我想使用Python字典。我的代码将每个功能读取为一个键,并将详细信息附加为值,但是我无法将人员添加为值。有人能帮忙吗
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)
编辑:固定代码缩进我只在以下情况下更改了
。。。其他
部分:
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)
你的缩进是错误的,模棱两可的,请修正它。它是错误的,我修正了它。我的错误谢谢,成功了。我仍在努力理解dict类型,但这个练习很有帮助