繁体   English   中英

Python:通过字典重构有序的文本文件

[英]Python: restructure an ordered text file via dictionary

我有一个要重组的文本文件。 该文件包含功能,功能描述(标签delim,描述符数量会有所不同)以及显示该功能的人员列表。 看起来像这样:

Feature1    detail1    detail2
Person1
Person2
Feature2    detail1    detail2    detail3
Person3

...而我只是想对其进行重组,以使每行只有一个功能,而人员则在描述符之后加到行上,因此看起来像这样:

 Feature1    detail1    detail2    Person1    Person2
 Feature2    detail1    detail2    detail3    Person3

我想使用Python字典。 我的代码将每个功能作为键读取,并将详细信息附加为值,但是我在将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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM