使用Python将文本文件转换为表

2024-10-01 07:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的文本文件

client interface: GigabitEthernet10/0/0.100 is up
active state: up
line state: up
vc state: down
...
colour: -

client interface: EthTrunk10.0.1 is up
active state: up
line state: up
vc state: down
...
colour: -

列表可以很长,大约有5000-10000行文本

有没有更好的办法把它转换成下面这样的表格形式

Client Interface           Active State    Line State    VC State    ...     Color
GigabitEthernet10/0/0.100     up              up           down                 -
EthTrunk10.0.1                up              up           down                 -

Tags: 文本client列表islineinterfaceactivedown
3条回答

假设您知道每个接口的列数:

import pandas as pd

df = pd.read_csv('text_filename.txt', sep=':', header=None)
N_COLS = 5

table_data = df.iloc[:,1].values.reshape(-1, N_COLS)
table_header = df.iloc[:n_cols,0].values

df = pd.DataFrame(table_data, columns=table_header)

输出:

               client interface active state line state vc state colour
0   GigabitEthernet10/0/0.100 is up           up         up     down      -
1              EthTrunk10.0.1 is up           up         up     down      -

我想这就是你要找的。因为我不知道每个接口包含的内容的确切数量,所以我首先找到了头,然后在里面循环

import pandas as pd
with open("sample.txt","r") as f:
    lines = f.readlines()
    lines = [l.strip() for l in lines]
n = len(lines)
headers = set()
for i in range(n):
    if(len(lines[i])>=3):
        key, value = lines[i].split(":")
        headers.add(key)
hlen = len(headers)
completeList = list()
for i in range(0,n,hlen):
    dictrow = dict()
    for j in range(hlen):
        if(j+i<n and len(lines[j+i])>=3):
            key,value = lines[j+i].split(":")
            dictrow[key] = value
    completeList.append(dictrow)
    dictrow = dict()
df = pd.DataFrame(completeList)

要导入熊猫,请使用以下方法:

import pandas as pd
df = pd.read_csv("filename.txt", sep=":", header=None)

相关问题 更多 >