【问题标题】:pandas.read_csv seperator with Regexpandas.read_csv 分隔符与正则表达式
【发布时间】:2023-01-03 02:48:26
【问题描述】:

我正在努力如何将文本文件解析为熊猫数据框。 我想使用 pandas.read_csv(sep='') 但我无法找出正确的配置,因为该文件使用空格作为分隔符,但也包含带分隔符的文本

示例数据行如下所示

<123> 2022-12-08T14:00:00 tag [id="451" tid="145] text message with commas

这是这个表的一行

type time part ids message
<123> 2022-12-08T14:00:00 tag [id="451" tid="145] text message with commas

【问题讨论】:

    标签: python pandas regex csv


    【解决方案1】:

    使用 read_csv 函数并将 sep 参数设置为 's+',这将按任意数量的空格拆分字段。

    import pandas as pd
    import csv
    
    df = pd.read_csv('data.txt', sep='s+', quoting=csv.QUOTE_NONE)
    
    print(df)
    

    【讨论】:

    • 这也会将消息字段内容“带逗号的文本消息”拆分为多个字段,不是吗?
    【解决方案2】:

    我建议不要使用 read_csv 函数来解析这个文本文件(因为我认为这是一个相当具体的用例,其中只考虑空格有时作为分隔符)。

    我写了一个小示例,展示了如何通过编程方式逐行读取并根据数据的一般逻辑结构进行解析来解析文件。基本上利用“ids”字段具有的方括号。

    这是代码示例:

    import pandas as pd
    
    data_list = []
    for line in open("example.csv","r"):
        # Separate the line by spaces into a list
        data = {}
        line = line.split(" ")
    
        # The first 3 elements correspond to "type", "time" and "part"
        data["type"] = line[0]
        data["time"] = line[1]
        data["part"] = line[2]
    
        # Then from the third position onward, concatenate each element until we find a closing square bracket
        # We will call this the id's field
        data['ids'] = ""
        for i in range(3,len(line)):
            data["ids"] = " ".join((data["ids"],line[i]))
            if line[i][-1] == "]":
                break
    
        # Finally, we will concatenate the rest of the elements into the "message" field
        data["message"] = " ".join(line[i+1:])
    
        # And we will append the data to a list
        data_list.append(data)
    
    # Now we will create a pandas dataframe from the list
    df = pd.DataFrame(data_list)
    
    print(df)
    

    【讨论】:

      【解决方案3】:

      你可以尝试使用re模块来解析数据:

      import re
      
      import pandas as pd
      
      s = '<123> 2022-12-08T14:00:00 tag [id="451" tid="145] text message with commas'
      
      pat = re.compile(r"(S+) (S+) (S+) ([.*?]) (.*)")
      
      df = pd.DataFrame(pat.findall(s), columns=["type", "time", "part", "ids", "message"])
      print(df)
      

      印刷:

          type                 time part                  ids                   message
      0  <123>  2022-12-08T14:00:00  tag  [id="451" tid="145]  text message with commas
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-06
        • 1970-01-01
        相关资源
        最近更新 更多