python中print中加个end参数的作用

当我们在python里打印一般用print来做,当我们想进行多次输出并且连续输出到同一行时,我们可以采用print后面的这个end参数填入空串来完成。比如在测试nlp的文本预测时,想连接输出预测的一句话,但是每次预测一个单词,就需要用到这个功能了。但是这个在python 3里才有用。

代码片断

 68         for iteration in range(self.num_iter):
 69             print('Iteration: %d'%iteration)
 70             model.fit(X, Y, batch_size=self.batch_size, epochs=self.num_epoch)
 71             # training 1 epoch, testing once
 72             test_idx = np.random.randint(len(self.input_chars))
 73             test_chars = self.input_chars[test_idx]
 74             print('test seed is: %s'%test_chars)
 75             print(test_chars, end='')
 76             for i in range(self.num_pred):
 77                 # test vectorized data
 78                 vec_test = np.zeros((1, self.seq_len, self.chars_count))
 79                 for i, ch in enumerate(test_chars):
 80                     vec_test[0, i, self.char2index[ch]] = 1
 81                 pred = model.predict(vec_test, verbose=0)[0]
 82                 pred_char = self.index2char[np.argmax(pred)]
 83                 print(pred_char, end='')
 84                 # continue to add new characters to generate new sequence
 85                 test_chars = test_chars[1:] + pred_char
 86             print('\n')

预测结果输入如下:

Iteration: 23
Epoch 1/1
1739/1739 [==============================] - 0s 41us/step - loss: 1.6302
test seed is: eiving dat
eiving dat  fties in ue the seduor ef at inn es onets sher no oh toa titi init sac es oon ta aod soptha s duti

猜你喜欢

转载自blog.csdn.net/lwc5411117/article/details/83448372