[英]Python: restructure an ordered text file via dictionary
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.
该文件包含功能,功能描述(标签delim,描述符数量会有所不同)以及显示该功能的人员列表。 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. 我想使用Python字典。 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 .
我的代码将每个功能作为键读取,并将详细信息附加为值,但是我在将Persons添加为值时遇到了麻烦 。 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 ... else
part: 我只更改了
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.