将带标题的列添加到制表符分隔的文本文件中?

时间:2013-07-08 13:45:31

标签: python csv

我意识到有一种方法可以使用'awk'添加列。

但我对这个替代方案并不熟悉,所以我想问一下是否有办法使用Python将列添加到制表符分隔的文本文件中?

具体来说,这是我需要添加一个列的场景:

我有以下格式的数据(我意识到格式可能不那么清晰,但手机,电子邮件和网站对应不同的列):

name    phone   email   website
D G Albright M.S.           
Lannister G. Cersei M.A.T., CEP 111-222-3333    cersei@got.com  www.got.com
Argle D. Bargle Ed.M.           
Sam D. Man Ed.M.    000-000-1111    dman123@gmail.com   www.daManWithThePlan.com
Sam D. Man Ed.M.            
Sam D. Man Ed.M.    111-222-333     dman123@gmail.com   www.daManWithThePlan.com
D G Bamf M.S.           
Amy Tramy Lamy Ph.D.    

我正在为第一列编写解析器。我想在一个名为'area'的新专栏中添加'实践领域',在这种情况下,ex将是'CEP'。我遍历文件,并使用pop函数将区域与第一列的其余部分分开。然后我将它添加到一个列表中,该列表在函数中消失,因为它没有添加到电子表格中。

这是我的剧本:

def parse_ieca_gc(s):  

    ### HANDLE NAME ELEMENT ######

    degrees = ['M.A.T.','Ph.D.','MA','J.D.',
               'Ed.M.', 'M.A.', 'M.B.A.', 
               'Ed.S.', 'M.Div.', 'M.Ed.', 
               'RN', 'B.S.Ed.', 'M.D.', 'M.S.']
    degrees_list = []

    # check whether the name string has 
    # an area of practice by 
    # checking if there's a comma separator
    if ',' in s['name']:

        # separate area of practice from name 
        # and degree and bind this to var 'area'
        split_area_nmdeg = s['name'].split(',')
        area = split_area_nmdeg.pop()

        # Split the name and deg by spaces. 
        # If there's a deg, it will match with one 
        # of elements and will be stored deg list.
        # The deg is removed name_deg list 
        # and all that's left is the name.
        split_name_deg = re.split('\s',split_area_nmdeg[0])
        for word in split_name_deg:
            for deg in degrees:
                if deg == word:
                    degrees_list.append(split_name_deg.pop())
                name = ' '.join(split_name_deg)

预期输出

name    phone   email   website    area   degrees
D G Albright                                                                      M.A.          
Lannister G. Cersei 111-222-3333    cersei@got.com  www.got.com    CEP    M.A.T.
Argle D. Bargle                                                             Ed.M.           
Sam D. Man  000-000-1111    dman123@gmail.com   www.daManWithThePlan.com   Ed.M.
Sam D. Man                                                                        Ed.M.         
Sam D. Man  111-222-333     dman123@gmail.com   www.daManWithThePlan.com      Ed.M.
D G Bamf                                                                          M.S.          
Amy Tramy Lamy                                                                   Ph.D.  

此代码也无效:

fieldnames = ['name','degrees','area','phone','email','website']
with open('ieca_first_col_fake_text.txt','r') as input:
    with open('new_col_dict.txt','w') as output:
        dict_writer = csv.DictWriter(output, fieldnames, delimiter = '\t')
        dict_reader = csv.DictReader(input, delimiter = '\t')
        #dict_writer.writeheader(fieldnames)
        for row in dict_reader:
            print row
            dict_writer.writerow(fieldnames)
            dict_writer.writerow(row)

2 个答案:

答案 0 :(得分:3)

在此处查看答案,制表符分隔文件类似于CSV,其中制表符为分隔符。

How to add a new column to a CSV file using Python?

答案 1 :(得分:1)

这就是我最终做的事情:

with open('ieca_first_col_fake_text.txt','r') as input, \
   open('new_col_dict.txt', 'w') as output:
        dict_reader = csv.DictReader(input, delimiter = '\t')
        dict_reader.fieldnames.append('area')
        dict_reader.fieldnames.append('degrees')

        dict_writer = csv.DictWriter(output, 
                                     fieldnames=dict_reader.fieldnames, 
                                     delimiter='\t')
        for row in dict_reader:
            print row
            dict_writer.writeheader()
            dict_writer.writerow(row)