Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从.txt(文本)文件解析表_Python_Python 3.x_Text_Text Parsing_Memory Profiling - Fatal编程技术网

Python 从.txt(文本)文件解析表

Python 从.txt(文本)文件解析表,python,python-3.x,text,text-parsing,memory-profiling,Python,Python 3.x,Text,Text Parsing,Memory Profiling,我从python分析器中获得了一些分析结果,如下所示: Filename: main.py Line # Mem usage Increment Line Contents ================================================ 30 121.8 MiB 121.8 MiB @profile(stream=f) 31 def parse_data(d

我从python分析器中获得了一些分析结果,如下所示:

Filename: main.py

Line #    Mem usage    Increment   Line Contents
================================================
    30    121.8 MiB    121.8 MiB   @profile(stream=f)
    31                             def parse_data(data):
    32    121.8 MiB      0.0 MiB       Y=data["price"].values
    33    121.8 MiB      0.0 MiB       Y=np.log(Y)
    34    121.8 MiB      0.0 MiB       features=data.columns
    35    121.8 MiB      0.0 MiB       X1=list(set(features)-set(["price"]))
    36    126.3 MiB      4.5 MiB       X=data[X1].values
    37    126.3 MiB      0.0 MiB       ss=StandardScaler()
    38    124.6 MiB      0.0 MiB       X=ss.fit_transform(X)
    39    124.6 MiB      0.0 MiB       return X,Y


Filename: main.py

Line #    Mem usage    Increment   Line Contents
================================================
    41    127.1 MiB    127.1 MiB   @profile(stream=f)
    42                             def linearRegressionfit(Xt,Yt,Xts,Yts):
    43    127.1 MiB      0.0 MiB       lr=LinearRegression()
    44    131.2 MiB      4.1 MiB       model=lr.fit(Xt,Yt)
    45    132.0 MiB      0.8 MiB       predict=lr.predict(Xts)
    46                             
现在,我需要获得这些结果用于绘图和其他目的。但是文本不是很方便。该表显示了逐行分析的结果。如何获取可用于从此表中获取任何行或列的pandas dataframe或表格版本


另外,我已经访问了
regex
consimonious
,但似乎无法在我的案例中使用它们。

这只是一点解析练习。通过使用标准的split()和一些小的调整,您可以在几行代码中获得一个非常干净的数据帧

txt = '''
Filename: main.py

Line #    Mem usage    Increment   Line Contents
================================================
    30    121.8 MiB    121.8 MiB   @profile(stream=f)
    31                             def parse_data(data):
    32    121.8 MiB      0.0 MiB       Y=data["price"].values
    33    121.8 MiB      0.0 MiB       Y=np.log(Y)
    34    121.8 MiB      0.0 MiB       features=data.columns
    35    121.8 MiB      0.0 MiB       X1=list(set(features)-set(["price"]))
    36    126.3 MiB      4.5 MiB       X=data[X1].values
    37    126.3 MiB      0.0 MiB       ss=StandardScaler()
    38    124.6 MiB      0.0 MiB       X=ss.fit_transform(X)
    39    124.6 MiB      0.0 MiB       return X,Y


Filename: main.py

Line #    Mem usage    Increment   Line Contents
================================================
    41    127.1 MiB    127.1 MiB   @profile(stream=f)
    42                             def linearRegressionfit(Xt,Yt,Xts,Yts):
    43    127.1 MiB      0.0 MiB       lr=LinearRegression()
    44    131.2 MiB      4.1 MiB       model=lr.fit(Xt,Yt)
    45    132.0 MiB      0.8 MiB       predict=lr.predict(Xts)
'''

import pandas as pd

lines = []
for line in txt.split('\n'):
    #print(line)
    if line.startswith('Filename'): continue
    if line.startswith('Line'): continue
    if line.startswith('='): continue
    if line == '': continue
    data = [i.strip() for i in line.split()]
    #Fix def lines
    if data[1] == 'def':
        data = [data[0],'','','','',' '.join(data[1:4])]

    data = [data[0], ' '.join(data[1:3]), ' '.join(data[3:5]), data[-1]]
    lines.append(data)

df = pd.DataFrame(lines, columns=['Line #', 'Mem usage', 'Increment','Line Contents'])

print(df)

   Line #  Mem usage  Increment                            Line Contents
0      30  121.8 MiB  121.8 MiB                       @profile(stream=f)
1      31                                          def parse_data(data):
2      32  121.8 MiB    0.0 MiB                   Y=data["price"].values
3      33  121.8 MiB    0.0 MiB                              Y=np.log(Y)
4      34  121.8 MiB    0.0 MiB                    features=data.columns
5      35  121.8 MiB    0.0 MiB    X1=list(set(features)-set(["price"]))
6      36  126.3 MiB    4.5 MiB                        X=data[X1].values
7      37  126.3 MiB    0.0 MiB                      ss=StandardScaler()
8      38  124.6 MiB    0.0 MiB                    X=ss.fit_transform(X)
9      39  124.6 MiB    0.0 MiB                                      X,Y
10     41  127.1 MiB  127.1 MiB                       @profile(stream=f)
11     42                        def linearRegressionfit(Xt,Yt,Xts,Yts):
12     43  127.1 MiB    0.0 MiB                    lr=LinearRegression()
13     44  131.2 MiB    4.1 MiB                      model=lr.fit(Xt,Yt)
14     45  132.0 MiB    0.8 MiB                  predict=lr.predict(Xts)
然后,当
“@profile”
位于
“行内容”
中时,可以拆分数据帧

例如:

split_idx = df[df['Line Contents'].str.startswith('@profile')].index
dataframes = []
for i, idx in enumerate(split_idx):
    try:
        dataframes.append(df.iloc[idx, split_idx[i+1]])
    except IndexError:
        dataframes.append(df.iloc[idx:])


print(dataframes[0])
print('======')
print(dataframes[1])

   Line #  Mem usage  Increment                            Line Contents
0      30  121.8 MiB  121.8 MiB                       @profile(stream=f)
1      31                                          def parse_data(data):
2      32  121.8 MiB    0.0 MiB                   Y=data["price"].values
3      33  121.8 MiB    0.0 MiB                              Y=np.log(Y)
4      34  121.8 MiB    0.0 MiB                    features=data.columns
5      35  121.8 MiB    0.0 MiB    X1=list(set(features)-set(["price"]))
6      36  126.3 MiB    4.5 MiB                        X=data[X1].values
7      37  126.3 MiB    0.0 MiB                      ss=StandardScaler()
8      38  124.6 MiB    0.0 MiB                    X=ss.fit_transform(X)
9      39  124.6 MiB    0.0 MiB                                      X,Y
10     41  127.1 MiB  127.1 MiB                       @profile(stream=f)
11     42                        def linearRegressionfit(Xt,Yt,Xts,Yts):
12     43  127.1 MiB    0.0 MiB                    lr=LinearRegression()
13     44  131.2 MiB    4.1 MiB                      model=lr.fit(Xt,Yt)
14     45  132.0 MiB    0.8 MiB                  predict=lr.predict(Xts)
======
   Line #  Mem usage  Increment                            Line Contents
10     41  127.1 MiB  127.1 MiB                       @profile(stream=f)
11     42                        def linearRegressionfit(Xt,Yt,Xts,Yts):
12     43  127.1 MiB    0.0 MiB                    lr=LinearRegression()
13     44  131.2 MiB    4.1 MiB                      model=lr.fit(Xt,Yt)
14     45  132.0 MiB    0.8 MiB                  predict=lr.predict(Xts)

现在还不完全清楚是要解析整个文本,还是每个表都有一个文本文件并要解析该表

如果要从每个表创建一个数据帧,使用
skiprows
参数到
read_fwf
应该可以工作(这会跳过文件中的非标准行,但会解析其余行)。在这里,我将第一个表的内容存储到一个文件
sample-1.txt
,并使用
read\u fwf
读取它

导入熊猫
df=pandas.read_fwf('sample-1.txt',skiprows=[1])
这将给出以下数据帧

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 4 columns):
Line #           10 non-null int64
Mem usage        9 non-null object
Increment        9 non-null object
Line Contents    10 non-null object
dtypes: int64(1), object(3)
memory usage: 392.0+ bytes
>>df.info()
范围索引:10个条目,0到9
数据列(共4列):
第10行非空int64
Mem用法9非空对象
增量9非空对象
行内容10非空对象
数据类型:int64(1),对象(3)
内存使用:392.0+字节
如果要将其拆分为单独的表,则必须在每次提到
Filename:main.py

时将该文件拆分为另一个解决方案

可以使用文本生成时间序列数据

示例代码:

from ttp import ttp
import pprint

data_1 = """
Line #    Mem usage    Increment   Line Contents
================================================
    30    121.8 MiB    121.8 MiB   @profile(stream=f)
    31                             def parse_data(data):
    32    121.8 MiB      0.0 MiB       Y=data["price"].values
    33    121.8 MiB      0.0 MiB       Y=np.log(Y)
    34    121.8 MiB      0.0 MiB       features=data.columns
    35    121.8 MiB      0.0 MiB       X1=list(set(features)-set(["price"]))
    36    126.3 MiB      4.5 MiB       X=data[X1].values
    37    126.3 MiB      0.0 MiB       ss=StandardScaler()
    38    124.6 MiB      0.0 MiB       X=ss.fit_transform(X)
    39    124.6 MiB      0.0 MiB       return X,Y
"""

data_2 = """
Line #    Mem usage    Increment   Line Contents
================================================
    41    127.1 MiB    127.1 MiB   @profile(stream=f)
    42                             def linearRegressionfit(Xt,Yt,Xts,Yts):
    43    127.1 MiB      0.0 MiB       lr=LinearRegression()
    44    131.2 MiB      4.1 MiB       model=lr.fit(Xt,Yt)
    45    132.0 MiB      0.8 MiB       predict=lr.predict(Xts)
    46    
"""

template = """
<vars>
timestamp = "get_timestamp_iso"
</vars>

<group macro="process">
Line_N    Mem_usage    Increment   Line_Contents {{ _headers_ }}
{{ @timestamp | set(timestamp) }}
</group>

<macro>
def process(data):
    # remove ===== matches
    if "====" in data["Line_N"]:
        return False
        
    # convert Increment to integer    
    incr = data.pop("Increment").split(" ")[0]
    data["Increment_MiB"] = float(incr) if incr else 0.0
    
    # convert Mem usage to integer 
    memuse = data.pop("Mem_usage").split(" ")[0]
    data["Mem_usage_MiB"] = float(memuse) if memuse else 0.0
    
    return data
</macro>
"""

parser = ttp(template=template)
parser.add_input(data_1)
parser.add_input(data_2)
parser.parse()
res = parser.result(structure="flat_list")
pprint.pprint(res)

# will print:
# [{'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 121.8,
#   'Line_Contents': '@profile(stream=f)',
#   'Line_N': '30',
#   'Mem_usage_MiB': 121.8},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'def parse_data(data):',
#   'Line_N': '31',
#   'Mem_usage_MiB': 0.0},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'Y=data["price"].values',
#   'Line_N': '32',
#   'Mem_usage_MiB': 121.8},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'Y=np.log(Y)',
#   'Line_N': '33',
#   'Mem_usage_MiB': 121.8},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'features=data.columns',
#   'Line_N': '34',
#   'Mem_usage_MiB': 121.8},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'X1=list(set(features)-set(["price"]))',
#   'Line_N': '35',
#   'Mem_usage_MiB': 121.8},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 4.5,
#   'Line_Contents': 'X=data[X1].values',
#   'Line_N': '36',
#   'Mem_usage_MiB': 126.3},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'ss=StandardScaler()',
#   'Line_N': '37',
#   'Mem_usage_MiB': 126.3},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'X=ss.fit_transform(X)',
#   'Line_N': '38',
#   'Mem_usage_MiB': 124.6},
#  {'@timestamp': '2020-08-01T21:57:51.734448+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'return X,Y',
#   'Line_N': '39',
#   'Mem_usage_MiB': 124.6},
#  {'@timestamp': '2020-08-01T21:57:51.738444+00:00',
#   'Increment_MiB': 127.1,
#   'Line_Contents': '@profile(stream=f)',
#   'Line_N': '41',
#   'Mem_usage_MiB': 127.1},
#  {'@timestamp': '2020-08-01T21:57:51.738444+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'def linearRegressionfit(Xt,Yt,Xts,Yts):',
#   'Line_N': '42',
#   'Mem_usage_MiB': 0.0},
#  {'@timestamp': '2020-08-01T21:57:51.738444+00:00',
#   'Increment_MiB': 0.0,
#   'Line_Contents': 'lr=LinearRegression()',
#   'Line_N': '43',
#   'Mem_usage_MiB': 127.1},
#  {'@timestamp': '2020-08-01T21:57:51.738444+00:00',
#   'Increment_MiB': 4.1,
#   'Line_Contents': 'model=lr.fit(Xt,Yt)',
#   'Line_N': '44',
#   'Mem_usage_MiB': 131.2},
#  {'@timestamp': '2020-08-01T21:57:51.738444+00:00',
#   'Increment_MiB': 0.8,
#   'Line_Contents': 'predict=lr.predict(Xts)',
#   'Line_N': '45',
#   'Mem_usage_MiB': 132.0}]
从ttp导入ttp
导入pprint
数据_1=“”
行#内存使用增量行内容
================================================
30 121.8 MiB 121.8 MiB@剖面图(流=f)
31 def解析_数据(数据):
32 121.8 MiB 0.0 MiB Y=数据[“价格”]。值
33 121.8 MiB 0.0 MiB Y=np.log(Y)
34 121.8 MiB 0.0 MiB功能=数据列
35 121.8 MiB 0.0 MiB X1=列表(设置(功能)-设置([“价格]))
36 126.3 MiB 4.5 MiB X=数据[X1]。值
37 126.3 MiB 0.0 MiB ss=StandardScaler()
38 124.6 MiB 0.0 MiB X=ss.fit_变换(X)
39 124.6 MiB 0.0 MiB返回X,Y
"""
数据_2=“”
行#内存使用增量行内容
================================================
41 127.1 MiB 127.1 MiB@配置文件(流=f)
42 def线性回归拟合(Xt、Yt、Xts、Yts):
43 127.1 MiB 0.0 MiB lr=线性回归()
44 131.2 MiB 4.1 MiB模型=lr.fit(Xt,Yt)
45 132.0 MiB 0.8 MiB预测=lr.predict(Xts)
46
"""
模板=“”“
timestamp=“获取时间戳”
行内存使用增量行内容{{{u头}
{{@timestamp | set(timestamp)}
def过程(数据):
#删除=====匹配项
如果数据[“行”]中的“==”:
返回错误
#将增量转换为整数
incr=data.pop(“增量”).split(“”[0]
数据[“增量”]=浮动(增量),如果增量为0.0
#将Mem用法转换为整数
memuse=data.pop(“Mem_用法”).split(“”[0]
数据[“Mem_usage_MiB”]=浮点(memuse),如果memuse else为0.0
返回数据
"""
解析器=ttp(模板=模板)
解析器.添加输入(数据1)
解析器.添加输入(数据2)
parser.parse()
res=parser.result(structure=“flat\u list”)
pprint.pprint(res)
#将打印:
#[{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:121.8,
#“行内容”:“@profile(stream=f)”,
#‘行’:‘30’,
#'Mem_usage_MiB':121.8},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#'行内容':'定义解析数据(数据):',
#‘行’:‘31’,
#'Mem_usage_MiB':0.0},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#“行内容”:“Y=数据[“价格”]。值”,
#'行N':'32',
#'Mem_usage_MiB':121.8},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#“行内容”:“Y=np.log(Y)”,
#‘行’:‘33’,
#'Mem_usage_MiB':121.8},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#“行内容”:“功能=数据.列”,
#‘行’:‘34’,
#'Mem_usage_MiB':121.8},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#“行内容”:“X1=列表(集合(功能)-集合([“价格”])”,
#‘行’:‘35’,
#'Mem_usage_MiB':121.8},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:4.5,
#“行内容”:“X=数据[X1]。值”,
#‘行’:‘36’,
#'Mem_usage_MiB':126.3},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#“行内容”:“ss=StandardScaler()”,
#‘行’:‘37’,
#'Mem_usage_MiB':126.3},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#“行内容”:“X=ss.fit\u变换(X)”,
#‘行’:‘38’,
#'Mem_usage_MiB':124.6},
#{@timestamp':'2020-08-01T21:57:51.734448+00:00',
#“增量_MiB”:0.0,
#“行内容”:“返回X,Y”,
#第39行:,
#'Mem_usage_MiB':124.6},
#{@timestamp':'2020-08-01T21:57:51.738444+00:00',
#“增量_MiB”:127.1,
#“行内容”:“@profile(stream=f)”,
#第41行:,
#'Mem_usage_MiB':127.1},
#{@timestamp':'2020-08-01T21:57:51.738444+00:00',
#“增量_MiB”:0.0,
#“行内容”:“def linearRegressionfit(Xt,Yt,Xts,Yts):”,
#‘行’:‘42’,
#'Mem_usage_MiB':0.0},
#{'@ti