程序: import numpy as np import csv import struct def main(): x = read_input(input('please input the path of the infile:')) #输入概率分布文件的路径 msg = create_msg(x, int(input('input the length:'))) #输入生成的信息长度,单位为B write_output(input('please input the path of the outfile:'), msg) #输入输出文件的路径 def read_input(file): with open(file, 'r') as csvfile: # 读取文件 reader = csv.reader(csvfile) column = [float(row[1]) for row in reader] # 读取csv文件存放概率的列至列表中 return column def create_msg(prob,msg_len): symbol_cumsum = np.cumsum(prob) # cumsum函数用法为当前列数据为前面所有列的和 symbol_random = np.random.uniform(size=msg_len) # uniform()方法将随机生成长度为msg_len的实数数组,它在 [0,1] 范围内 msg = np.searchsorted(symbol_cumsum, symbol_random) return msg def write_output(fout,msg): with open(fout, 'wb') as fout: for i in msg: fout.write(struct.pack('B', i)) if __name__ == "__main__": main() 举例 input_prob.csv是一个概率分布文件,第一列为256个符号:0~255,第二列为每一个符号的概率,概率相等,均为1/256,前十一行如下: 运行程序: 3.输出结果: 用HxD编辑器打开out.dat结果如下: