关于用pandas.read_csv函数 清洗txt文本数据的问题

文件如下图所示,是药品的说明书

这个文本文件里有几十万个这样的商品资料
我要把这个文本文件处理成一个表格

就是把每一行的说明书抬头【】里的文字,作为pandas表格的列名,把后面的内容作为这一列的内容
有简便的方法实现吗

你这是公开数据集吗?如果是,麻烦也发我个连接,如果不是那就算了。我刚才写了份代码,应该是能实现你的要求

# -*- coding:utf-8 -*-
import pandas as pd
import re
import numpy as np
import os
import glob
pd.set_option('display.max_columns', None)  #设置显示总行数


def max_columns_dataframe(data_path):
    #返回药品说明书中最多的列
    num = []
    for i,path in enumerate(data_path): #
        df = pd.read_csv(path,encoding="utf-8")
        columns = df[df.columns.tolist()[0]].apply(lambda x:str(x)[:str(x).find("】")].replace("【","")) 
        num.append(len(columns))
    file = data_path[num.index(max(num))] #找出列明最多的文件
    df = pd.read_csv(file,encoding="utf-8")
    columns = df[df.columns.tolist()[0]].apply(lambda x:str(x)[:str(x).find("】")].replace("【","")) 
    columns_name = columns.values.tolist()
    index = re.findall("\d", df.columns.tolist()[0], flags=0)[0]  #获取商品ID
    dicts = dict.fromkeys(columns_name)
    pf = pd.DataFrame([dicts],index=[index])  #创建新datafrom    
    return pf.dropna()

data_path = glob.glob("*txt")
pf = max_columns_dataframe(data_path)
#添加数据
for file in data_path:
    df = pd.read_csv(file,encoding="utf-8")
    columns = df[df.columns.tolist()[0]].apply(lambda x:str(x)[:str(x).find("】")].replace("【",""))
    columns_name = columns.values.tolist()
    index = re.findall("\d", df.columns.tolist()[0], flags=0)[0]  #获取商品ID
    dicts = dict.fromkeys(columns_name)
    tf = pd.DataFrame([dicts],index=[index])  #创建新datafrom
    for i,j in zip(columns_name,df.values.tolist()):
        if j[0].find(i) == 1:
            #tf[i] = df.values.tolist()[0][0].split("】")[1]
            tf[i] = j[0].split("】")[1]
        else:
            tf[i] = np.nan
    pf = pd.concat([pf,tf])
pf.sort_index(inplace=True) #根据索引排序
pf.to_csv("药品说明书预处理.csv")    

 

1. 新建一个字典,键是说明书中【】里的文字,每个键值是一个空的列表;

2. 遍历所有的说明书,用正则解析出每一个键值对,添加到字典同名键的列表里;

3. 将字典写入csv文件,或者先把字典转成DataFrame,再用to_csv的方法写到csv文件中。

第2步的正则解析是重点,可以参考我的这篇博文:《一篇短文,尽除沉疴,彻底破解正则恐惧症!》 https://xufive.blog.csdn.net/article/details/106468205