欢迎访问宙启技术站
智能推送

Python中关于tensorflow.core.example.example_pb2_EXAMPLE的随机中文标题示例(20条)

发布时间:2023-12-29 07:22:44

import random

def random_chinese_title():

    # 随机生成中文标题

    # 标题由1到5个汉字组成,每个汉字由3个字节表示

    title_len = random.randint(1, 5)

    title_bytes = bytearray(title_len*3)

    for i in range(title_len):

        # 生成一个汉字的unicode码

        #  个汉字的范围:\u4e00-\u9fa5

        # 后续汉字的范围:\u3007\u3021-\u3029\u3038-\u4dff\u9fa6-\u9fbb\u9fbc-\ufaff\ufe30-\ufe4f\ufe50-\ufe6b\ufe70-\ufefc

        if i == 0:

            #  个汉字的范围:\u4e00-\u9fa5

            title_bytes[i*3:i*3+3] = random.randint(0x4e00, 0x9fa5).to_bytes(3, 'big')

        else:

            # 后续汉字的范围:\u3007\u3021-\u3029\u3038-\u4dff\u9fa6-\u9fbb\u9fbc-\ufaff\ufe30-\ufe4f\ufe50-\ufe6b\ufe70-\ufefc

            range_start = [0x3007, 0x3021, 0x3038, 0x9fa6, 0x9fbc, 0xfe30, 0xfe50, 0xfe70]

            range_end = [0x3029, 0x4dff, 0x9fbb, 0xfaff, 0xfefc, 0xfe4f, 0xfe6b, 0xfefc]

            range_index = random.randint(0, len(range_start)-1)

            title_bytes[i*3:i*3+3] = random.randint(range_start[range_index], range_end[range_index]).to_bytes(3, 'big')

    # 将字节转换为unicode字符串

    title = title_bytes.decode(encoding='unicode_escape')

    return title

# 生成20个随机中文标题示例

for i in range(20):

    title = random_chinese_title()

    print(title)

# 使用例子

import tensorflow as tf

from tensorflow.core.example import example_pb2

def create_example(input_title, input_text):

    # 创建一个example对象

    example = example_pb2.Example()

    # 设置标题和文本

    example.features.feature['title'].bytes_list.value.extend([input_title.encode()])

    example.features.feature['text'].bytes_list.value.extend([input_text.encode()])

    return example

def read_example(example):

    # 读取example中的标题和文本

    title = example.features.feature['title'].bytes_list.value[0].decode()

    text = example.features.feature['text'].bytes_list.value[0].decode()

    return title, text

# 创建一个example对象

example = create_example("中文标题示例", "这是一篇示例文本。")

# 将example序列化为字符串

serialized_example = example.SerializeToString()

# 反序列化为example对象

deserialized_example = example_pb2.Example.FromString(serialized_example)

# 读取标题和文本

title, text = read_example(deserialized_example)

print("原始标题:", title)

print("原始文本:", text)