python常用

1 字符串中加空格
" ".join(list(user_q))

2 dic转json

hjson = json.dumps(stand_q_dic, ensure_ascii=False)

3 str转json

string
hjson = json.loads(psrser_json)
message = hjson["message"]

文件
fp = open('data_for_bigru/char_c2i_128.json', 'r+')
dict = json.load(fp)
print(dict)

4 将相同id的其他字段,放在一起

standq_dic = {}
for i in range(1, sheet1.nrows):
    query = sheet1.cell(i, 0).value
    type = sheet1.cell(i, 1).value
    standq = sheet1.cell(i, 2).value
    if type == "知识库":
        value = standq_dic.get(standq, 0)
        temp_list = []
        if value == 0:
            temp_list.append(query)
            standq_dic[standq] = temp_list
        else:
            value.append(query)
            standq_dic[standq] = value
5 dic按照key还是value排序,下例d[1]表示按照value进行排序
standq_count_dic = {}
for key in standq_dic:
    standq_count_dic[key] = len(standq_dic[key])

result = sorted(standq_count_dic.items(), key=lambda d: d[1], reverse=True)
for element in result:
    print(element)

https://blog.csdn.net/penglei0901/article/details/37494721

你可能感兴趣的:(Python)