如何读取文件中图并且写入文件

问题分析:

convert Chem to Chem.bss
Example:
Chem:
t # 0//表示第0个图的ID是0
v 0 1//第0个顶点的标签是1
v 1 2
v 2 1
v 3 1
e 0 1 1//从0到1的边的标签是1
e 1 2 1
e 2 3 1
t # 1
v 0 1
v 1 2
v 2 1
v 3 1
e 0 1 1
e 1 2 1
e 2 3 1

Chem.bss//将以上文件的格式转变为下面的格式
0
4 3 //第0个图的顶点有4个,边有3个
1
2
1
1
0 1 1
1 2 1 
2 3 1
1
4 3 
1
2
1
1
0 1 1
1 2 1 
2 3 1

如何统计顶点和统计边的个数:

#author:wang hao time:2021.5.4
def count_ve(t_list):
    length = len(t_list)
    count = {}
    this_t = 't # 0'
    v=0 # 记录点
    e=0 # 记录边

    for i, string in enumerate(t_list):
        # 模糊匹配
        if string.find('t #') != -1: 
            next_t = string
            count.update({this_t:{'v':v,'e':e}})#更新字典的value
            v=0
            e=0
            this_t = next_t
        elif string.find('v') != -1:
            v += 1
        elif string.find('e') != -1:
            e += 1
        
        # 最后一个t单独加进去
        if i == length-1:
            count.update({next_t:{'v':v,'e':e}})

    return count

with open('CHEM', 'r') as file:
    line_string = -1
    string_list = list()
    for line in file:
        line_string = str(line.rstrip())
        string_list.append(line_string) 
#a file to be writien
file_write = open('Test','w')
with open('CHEM','r') as file:
    nE = 0
    nV = 0
    for line in file:
        if line[0]=='t':#line[0]中存储t # 1
            graph_ID = line.rstrip()[4:]#记录下图编号 例如1
            print(line.rstrip()[4:], file = file_write)
            nV = graph_dict["t # " + str(graph_ID)]['v']
            nE = graph_dict["t # " + str(graph_ID)]['e']
            print(str(nV)+" "+str(nE), file = file_write)
        elif line[0]=='v':
            #case:len(line)==6
            if len(line)==6:
                print(line.rstrip('\n')[4:].rstrip('\n'), file = file_write)
            #case:len(line)==7
            if len(line)==7:
                print(line.rstrip()[5:], file= file_write)
        elif line[0]=='e':
            print(line.rstrip()[2:], file = file_write)
print("Complete!")
file.close()

以上文件路径在我的电脑中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值