代码之家  ›  专栏  ›  技术社区  ›  user026

如何从文本中分离特定的字符串并将它们作为列名添加?

  •  0
  • user026  · 技术社区  · 5 年前

    想象一下我有一个这样的txt文件:

    '''
    Useless information 1
    Useless information 2
    Useless information 3
    Measurement:
    Len. (cm)   :length of the object
    Hei. (cm)   :height of the object
    Tp.         :type of the object
    ~A DATA
    10  5   2
    8   7   2
    5   6   1
    9   9   1
    '''
    

    我想把“~A DATA”下面的值作为一个数据帧。虽然我的列中已经有了一些乱七八糟的数据行,但我已经看到了:

    with open(r'C:\Users\Lucas\Desktop\...\text.txt') as file:
        for line in file:
            if line.startswith('~A'):
               measures = line.split()[len(line):]
               break
    
        df = pd.read_csv(file, names=measures, sep='~A', engine='python')
    
    newdf = df[0].str.split(expand = True)
    
    newdf()
        0  1  2
    0  10  5  2
    1   8  7  2
    2   5  6  1
    3   9  9  1
    

    现在,我想把文本中的'Len'、'Hei'和'Tp'作为列名放在DataFrame上。只有这些测量代码(没有相应的字符串)。我怎么能做到这一点呢?

        Len  Hei  Tp
      0  10   5   2
      1   8   7   2
      2   5   6   1
      3   9   9   1
    

    解决方案之一是将字符串“Measurement”(或以“Len…”开头)下面的每一行拆分到字符串“~A”(或以“Tp”结束)上方的每一行。然后把我们得到的每一条线分开。但我不知道怎么做。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Anant Mittal    5 年前

    解决方案1: 如果您想从文本文件本身中删除列名,那么您需要知道列名信息是从哪一行开始的,然后逐行读取文件并对您知道的以列名作为文本的特定行进行处理。

    为了回答您所问的具体问题,我们假设变量 line line = Len. (cm) :length of the object ,您可以进行基于regex的拆分,其中,您可以拆分除数字和字母以外的任何特殊符号。

    import re
    splited_line = re.split(r"[^a-zA-Z0-9]", line) #add other characters which you don't want
    print(splited_line)
    

    ['Len', ' ', 'cm', '   ', 'length of the object']
    

    此外,要获得列名,从列表中选择第一个元素作为 splited_line[0]

    解决方案2: 如果你已经知道列名,你可以

    df.columns = ['Len','Hei','Tp']

    In [34]: f = open('text.txt', "rb") 
        ...: flag = False 
        ...: column_names = [] 
        ...: for line in f: 
        ...:     splited_line = re.split(r"[^a-zA-Z0-9~]", line.decode('utf-8')) 
        ...:     if splited_line[0] == "Measurement": 
        ...:         flag = True 
        ...:         continue 
        ...:     elif splited_line[0] == "~A": 
        ...:         flag = False 
        ...:     if flag == True: 
        ...:         column_names.append(splited_line[0])