python常用算法

1.根据二维坐标位置对字符排序(从左往右,从上往下)

def sort_indice(self, arr, ref):
    indices = []
    for ch in arr:
        info = ref[:,:,ch]
        pos = np.where(info >= info.max())
        indices.append((ch, (pos[0][0],pos[1][0])))
    chars_pos = sorted(indices, key=lambda x: (x[1][1], x[1][0]))
    chars = np.array([char[0] for char in chars_pos])
    return chars

2. 根据字符位置(X,Y) ,在vis_arr中绘出字符打印顺序

cv2.putText(vis_arr, idx, (int(Y), int(X)), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255,0,0), 1)

3.torch.where用法和矩阵点乘

def check_2(self, out_rank, prob_rank):
    # 2 unknown class in last pos of seq will be removed
    ref = out_rank[1]
    y = torch.ones(ref.shape, dtype=torch.long).cuda()
    x = torch.zeros(ref.shape, dtype=torch.long).cuda()
    z = torch.where(ref != 1, y, x)
    prob_rank = torch.mul(prob_rank, z)

4.检查字符串是否为中文字符串

def isChinese(word):
    for ch in word:
        if '\u4e00' <= ch <= '\u9fff':
            return True
    return False

5.读写txt文件,os.listdir用法

import os
def construct():
    file_name = 'abc.txt'
    gt_path = '/home/gt'
    filelist = os.listdir(gt_path)
    for i, gt_file in enumerate(filelist):
        with open(gt_file) as f1:
            raw = f1.readlines()
            label = raw[0]
        with open(file_name, "a+", encoding='utf-8') as f2:
            f2.write('%s\n' % label)

6.读写json文件

import json
def read_json():
    file = 'abc.json'
    with open(file, 'r+', encoding='utf8') as f1:
        data = json.load(f1)
    with open(file, 'w+') as f1:
        list = [1]
        json.dump(list, f1)

7.读jsonline文件

import jsonlines
def read_jsonl():
    jsonl_file = 'train.jsonl'
    with open(jsonl_file, 'r+', encoding='utf8') as f1:
        for item in jsonlines.Reader(f1):
            print(item)

8.读csv文件

def read_csv(self):
    file = 'submit.csv'
    with open(file) as f1:
        reader = csv.reader(f1)
        header = next(reader)
        for row in reader:
            print(row)

9.节点间距离,聚类(近似)融合

def merge_neigh(idx, nodes):
    node = nodes[idx]
    for item in nodes.items():
        if item[0] == idx:
            continue
        if (node[0]-item[1][0])**2 + (node[1]-item[1][1])**2 <= 2:
            del nodes[idx]
            break
    return nodes

if __name__ == '__main__':
    nodes = {0: (1,1), 1: (2,2), 2: (6,5), 3: (6,6), 4: (7,7)}
    for i in range(len(nodes)):
        node = merge_neigh(i, nodes)
    print(nodes)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值