【问题标题】:Is there a way to read data into R or Python and split it by number of characters?有没有办法将数据读入 R 或 Python 并按字符数拆分?
【发布时间】:2020-10-22 22:04:00
【问题描述】:

假设我有许多字段,它们各自的字符长度。第一个字段是长度为 10 的 ID,第二个字段是长度为 20 的电话号码,依此类推。可以根据长度设置分隔符吗?

数据没有任何结构,因此为了读取它,我必须找到一种在读取时构建表格的方法。它是一个纯文本文件。但是,我确实对每个字段都有各自的字符长度。我以前没有做过这样的事情,所以在我花几个小时之前我想看看这是否可能。

【问题讨论】:

  • 在 R 中有 read.fwf() 函数。我确信 Python 中也有类似的东西。
  • 哇从来不知道这个。看起来这可能有效。
  • pd.read_fwf() 用于 python 中的熊猫
  • 在 python 中,您可以使用字符串进行索引,例如id_field = message[0:10]

标签: python r dataframe text


【解决方案1】:

在 python 中,你可以对字符串进行切片。

msg = "ID12345678PHONE123456789012345BLOB"
_id = msg[:10]
phone = msg[10:30]
blob = msg[30:34]
print(_id, phone, blob)

结果

ID12345678 PHONE123456789012345 BLOB

选项2:如果你以二进制模式打开文件,得到bytes字符串,你可以使用struct模块解压。

import struct

msg = b"ID12345678PHONE123456789012345BLOB"
_id, phone, blob = struct.unpack("10s20s4s", msg)
print(_id, phone, blob)

【讨论】:

    【解决方案2】:

    在python中确实应该很简单

    pandas你可以使用简单的函数read_fwf()

    例如这样的事情

    我的文件.txt

    1name1surname1
    2name2surname2
    

    列大小为[1, 5, 8] 可以这样读取文件

    import pandas as pd
    df = pd.read_fwf("myfile.txt", widths=[1, 5, 8])
    

    此功能的详细信息here

    如果你想自己解析文件,这也很简单:

    import pandas as pd
    # column name + size
    meta_data = [('id',1),('name',5),('surname',8)]
    
    def my_parser(line):
        curr_dict = {}
        start=0
        end=0
        for meta in meta_data:
            end = meta[1] + end
            curr_dict[meta[0]] = line[start:end]
            start = end
        return curr_dict
            
       
    
    with open("myfile.txt", "r") as f_o:
        lines = f_o.readlines()
        dicts = []
        for line in lines:
             dicts.append(my_parser(line))
    
    pd.Dataframe(dicts)
    

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2020-10-11
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      相关资源
      最近更新 更多