# -*- coding: utf-8 -*-from __future__ import absolute_import, division, print_function, unicode_literals   # 把下一个新版本的特性导入到当前版本
from sklearn.model_selection import train_test_split
import tensorflow.compat.v1 as tf
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
import numpy as np
import unicodedata
import re   # 正则处理
### 代码.     匹配除换行符以外的任意字符
### 代码\w    匹配字母/数字/下划线/汉字
### 代码\s    匹配任意的空白符
### 代码\d    匹配数字
### 代码\b    匹配单词的开始或结束
### 代码^     匹配字符串的开始
### 代码$     匹配字符串的结束
### 代码*     重复零次或更多次,优先更多
### 代码+     重复一次或更多次,优先更多
### 代码?    重复零次或一次,优先一次
### 代码{n}   重复n次
### 代码{n,}  重复n次或更多次
### 代码{n,m} 重复n到m次
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("^匹配",str)) #字符串开始位置与匹配规则符合就匹配且打印匹配内容,否则不匹配,返回值是list
### ['匹配']
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("[^a-z]",str)) #反取,匹配出除字母外的字符,返回值是list
### ['匹', '配', '规', '则', '这', '个', '字', '符', '串', '是', '否', '匹', '配', '规', '则', '则', '则', '则', '则']
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("则$",str)) #字符串结束位置与则符合就匹配,否则不匹配,返回值是list
### ['则']
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("则*",str)) #星号前面的一个字符可以是0次或多次,返回值是list
### print(re.findall("规则*",str)) #星号前面的一个字符可以是0次或多次,返回值是list
### ['', '', '', '', '则', '', '', '', '', '', '', '', '', '', '', '', '', '', '则则', '', '', '则则则', '']
### ['规则', '规则则']
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("则+",str)) #加号前面的一个字符可以是1次或多次,返回值是list
### print(re.findall("规则+",str)) #加号配前面的一个字符可以是1次或多次,返回值是list
### ['则', '则则', '则则则']
### ['规则', '规则则']
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("则?",str)) #问号前面的一个字符可以是0次或1次,返回值是list
### print(re.findall("规则?",str)) #问号前面的一个字符可以是0次或1次,返回值是list
### ['', '', '', '', '则', '', '', '', '', '', '', '', '', '', '', '', '', '', '则', '则', '', '', '则', '则', '则', '']
### ['规则', '规则']
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("则{2}",str)) #匹配前一个字符2次,返回值是list
### print(re.findall("规则{1,2}",str)) #匹配前一个字符1-2次,返回值是list
### ['则则', '则则']
### ['规则', '规则则']
###
### str="匹配s规则这s个字符串是否s匹配f规则则re则则则"
### print(re.findall("匹配[s,f]规则",str)) #匹配字符后,只有符合[]中任意字符均可,返回值是list
### ['匹配s规则', '匹配f规则']
###
### str="匹配s规则这s个字符串4是否s匹配3f规则则re则则2则"
### print(re.findall("\d",str)) #匹配字符串所有的数字,返回值是list
### ['4', '3', '2']
###
### str="匹配s规则这s个字符串455是否s匹配3f规则则re则则2则"
### print(re.findall("\d+",str)) #匹配字符串中一位或多位数字,返回值是list
### ['455', '3', '2']
###
### str="匹配s规则这s个字符串455是否s匹配3f规则则re则则2则"
### print(re.findall("\D",str)) #匹配字符串中非数字,返回值是list
### ['匹', '配', 's', '规', '则', '这', 's', '个', '字', '符', '串', '是', '否', 's', '匹', '配', 'f', '规', '则', '则', 'r', 'e', '则', '则', '则']
###
### str="匹配s规则这s个字 符 串 \n \t \f \v455是否s匹配3f规则则re则则2则"
### print(re.findall("\s",str)) #匹配字符串空白字符(\t\n\r\f\v),返回值是list
### [' ', ' ', ' ', '\n', ' ', '\t', ' ', '\x0c', ' ', '\x0b']
###
### str="匹配s规则这s个字 符 串 \n \t \f \v455是"
### print(re.findall("\S",str)) #匹配字符串非空白字符(\t\n\r\f\v),返回值是list
### ['匹', '配', 's', '规', '则', '这', 's', '个', '字', '符', '串', '4', '5', '5', '是']
###
### str="匹配s规则这s个_字 S符 串-455是"
### print(re.findall("\w",str)) #匹配字符串下划线,汉字,字母,数字,返回值是list
### ['匹', '配', 's', '规', '则', '这', 's', '个', '_', '字', 'S', '符', '串', '4', '5', '5', '是']
###
### str="匹配s规则这s个_字 S符 串-455是"
### print(re.findall("\W",str)) #匹配字符串非下划线,汉字,字母,数字,返回值是list
### [' ', ' ', '-']
###
### str="a3a3ddd"
### print(re.search("(a3)+",str).group()) #匹配一个或多个a3
### a3a3
###
### str="a3死a3d有dd"
### print(re.findall(r"死|有+",str)) #匹配|前后一个字符均可
### ['死', '有']
###
### str="hello egon bcd egon lge egon acd 19"
### r=re.match("h\w+",str) #match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None,非字母,汉字,数字及下划线分割
### print(r.group()) # 获取匹配到的所有结果,不管有没有分组将匹配到的全部拿出来
### print(r.groups()) # 获取模型中匹配到的分组结果,只拿出匹配到的字符串中分组部分的结果
### print(r.groupdict())  # 获取模型中匹配到的分组结果,只拿出匹配到的字符串中分组部分定义了key的组结果
### hello
### ()
### {}
###
### r2=re.match("h(\w+)",str) #match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
### print(r2.group())
### print(r2.groups())
### print(r2.groupdict())
### hello
### ('ello',)
### {}
###
### r3=re.match("(?P<n1>h)(?P<n2>\w+)",str)  #?P<>定义组里匹配内容的key(键),<>里面写key名称,值就是匹配到的内容
### print(r3.group())
### print(r3.groups())
### print(r3.groupdict())
### hello
### ('h', 'ello')
### {'n1': 'h', 'n2': 'ello'}
###
### str="hello egon bcd egon lge egon acd 19"
### r=re.search("h\w+",str) #match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None,非字母,汉字,数字及下划线分割
### print(r.group()) # 获取匹配到的所有结果,不管有没有分组将匹配到的全部拿出来
### print(r.groups()) # 获取模型中匹配到的分组结果,只拿出匹配到的字符串中分组部分的结果
### print(r.groupdict())  # 获取模型中匹配到的分组结果,只拿出匹配到的字符串中分组部分定义了key的组结果
### hello
### ()
### {}
###
### r2=re.search("h(\w+)",str) #match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
### print(r2.group())
### print(r2.groups())
### print(r2.groupdict())
### hello
### ('ello',)
### {}
###
### r3=re.search("(?P<n1>h)(?P<n2>\w+)",str)  #?P<>定义组里匹配内容的key(键),<>里面写key名称,值就是匹配到的内容
### print(r3.group())
### print(r3.groups())
### print(r3.groupdict())
### hello
### ('h', 'ello')
### {'n1': 'h', 'n2': 'ello'}
###
### r=re.findall("\d+\w\d+","a2b3c4d5") #浏览全部字符串,匹配所有合规则的字符串,匹配到的字符串方到一个列表中
### print(r)
### ['2b3', '4d5'] #匹配成功的字符串,不再参与下次匹配,所以3c4也符合规则但是没有匹配到
###
### r=re.findall("","a2b3c4d5") #浏览全部字符串,匹配所有合规则的字符串,匹配到的字符串方到一个列表中
### print(r)
### ['', '', '', '', '', '', '', '', ''] #如果没有写匹配规则,也就是空规则,返回的是一个比原始字符串多一位的空字符串列表,如上是8个字符,返回是9个空字符
###
### r=re.findall("(ca)*","ca2b3caa4d5") #浏览全部字符串,匹配所有合规则的字符串,匹配到的字符串方到一个列表中
### print(r)
### ['ca', '', '', '', 'ca', '', '', '', '', '']#用*号会匹配出空字符
###
### r=re.findall("a\w+","ca2b3 caa4d5") #浏览全部字符串,匹配所有合规则的字符串,匹配到的字符串方到一个列表中
### print(r)
### ['a2b3', 'aa4d5']#匹配所有合规则的字符串,匹配到的字符串放入列表
###
### r=re.findall("a(\w+)","ca2b3 caa4d5") #有分组:只将匹配到的字符串里,组的部分放到列表里返回
### print(r)
### ['2b3', 'a4d5']#返回匹配到组里的内容返回
###
### r=re.findall("(a)(\w+)","ca2b3 caa4d5") #有多分组:只将匹配到的字符串里,组的部分放到一个元组中,最后将所有元组放到一个列表里返回
### print(r)
### [('a', '2b3'), ('a', 'a4d5')]#返回的是多维数组
###
### r=re.findall("(a)(\w+(b))","ca2b3 caa4b5") #分组中有分组:只将匹配到的字符串里,组的部分放到一个元组中,先将包含有组的组,看作一个整体也就是一个组,把这个整体组放入一个元组里,然后在把组里的组放入一个元组,最后将所有组放入一个列表返回
### print(r)
### [('a', '2b', 'b'), ('a', 'a4b', 'b')]#返回的是多维数组
###
### r=re.findall("a(?:\w+)","a2b3 a4b5 edd") #?:在有分组的情况下,不只拿分组里的字符串,拿所有匹配到的字符串,注意?:只用于不是返回正则对象的函数如findall()
### print(r)
### ['a2b3', 'a4b5']
###
### r=re.split("a\w","sdfadfdfadsfsfafsff")
### print(r)
### r2=re.split("a\w","sdfadfdfadsfsfafsff",maxsplit=2)
### print(r2)
### ['sdf', 'fdf', 'sfsf', 'sff']
### ['sdf', 'fdf', 'sfsfafsff']
###
### r=re.sub("a\w","替换","sdfadfdfadsfsfafsff")
### print(r)
### sdf替换fdf替换sfsf替换sff
###
### a,b=re.subn("a\w","替换","sdfadfdfadsfsfafsff") #替换匹配成功的指定位置字符串,并且返回替换次数,可以用两个变量分别接受
### print(a) #返回替换后的字符串
### print(b) #返回替换次数
### sdf替换fdf替换sfsf替换sffimport os
import io
import timetf.disable_v2_behavior()
tf.enable_eager_execution()### 下载文件
path_to_zip = tf.keras.utils.get_file('spa-eng.zip', origin='https://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip',extract=True)
path_to_file = os.path.dirname(path_to_zip)+"/spa-eng/spa.txt"### 字符转换
def unicode_to_ascii(s):return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')### normalize() 第一个参数指定字符串标准化的方式,NFC表示字符应该是整体组成,而NFD表示字符应该分解为多个组合字符表示。### s1 = 'Spicy Jalape\u00f1o'### s2 = 'Spicy Jalapen\u0303o'### s1### 'Spicy Jalape?o'### s2### 'Spicy Jalape?o'### s1 == s2### False### len(s1)### 14### len(s2)### 15### t1 = unicodedata.normalize('NFC', s1)### t2 = unicodedata.normalize('NFC', s2)### t1 == t2### True### print(ascii(t1))### 'Spicy Jalape\xf1o'### t3 = unicodedata.normalize('NFD', s1)### t4 = unicodedata.normalize('NFD', s2)### t3 == t4### True### print(ascii(t3))### 'Spicy Jalapen\u0303o'def preprocess_sentence(w):w = unicode_to_ascii(w.lower().strip())w = re.sub(r"([?.!,?])", r" \1 ", w)   # 在标点和单词间增加空格w = re.sub(r'[" "]+', " ", w)w = re.sub(r"[^a-zA-Z?.!,?]+", " ", w)   # 除指定字符外,其他都用空格替换w = w.rstrip().strip()   # 删除末尾空格,开头空格w = '<start> ' + w + ' <end>'return wen_sentence = u"May I borrow this book?"
sp_sentence = u"?Puedo tomar prestado este libro?"
print("英文:    ",preprocess_sentence(en_sentence))
print("西班牙文:",preprocess_sentence(sp_sentence).encode('utf-8'))### 返回单词组
def create_dataset(path, num_examples):lines = io.open(path, encoding='UTF-8').read().strip().split('\n')word_pairs = [[preprocess_sentence(w) for w in l.split('\t')]  for l in lines[:num_examples]]return zip(*word_pairs)en, sp = create_dataset(path_to_file, None)
print("英文:    ",en[-1])
print("西班牙文:",sp[-1])def max_length(tensor):return max(len(t) for t in tensor)def tokenize(lang):lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(filters='')lang_tokenizer.fit_on_texts(lang)tensor = lang_tokenizer.texts_to_sequences(lang)tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor,padding='post')return tensor, lang_tokenizerdef load_dataset(path, num_examples=None):targ_lang, inp_lang = create_dataset(path, num_examples)input_tensor, inp_lang_tokenizer = tokenize(inp_lang)target_tensor, targ_lang_tokenizer = tokenize(targ_lang)return input_tensor, target_tensor, inp_lang_tokenizer, targ_lang_tokenizernum_examples = 30000
input_tensor, target_tensor, inp_lang, targ_lang = load_dataset(path_to_file, num_examples)
max_length_targ, max_length_inp = max_length(target_tensor), max_length(input_tensor)
input_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)print("训练集长度:",len(input_tensor_train), "训练集值长度:",len(target_tensor_train), "验证集长度:",len(input_tensor_val), "验证值集长度:",len(target_tensor_val))def convert(lang, tensor):for t in tensor:if t!=0:print ("%s ---------> %s" % (fixedlen(str(t)), lang.index_word[t]))def fixedlen(inputstr):if len(inputstr)<10:inputstr=" "*(10-len(inputstr))+inputstrreturn inputstrprint ("输入语种,索引与单词映射")
convert(inp_lang,   input_tensor_train[0])
print ()
print ("输出语种,索引与单词映射")
convert(targ_lang, target_tensor_train[0])BUFFER_SIZE = len(input_tensor_train)
BATCH_SIZE = 64
steps_per_epoch = len(input_tensor_train)//BATCH_SIZE
embedding_dim = 256
units = 1024
vocab_inp_size = len(inp_lang.word_index)+1
vocab_tar_size = len(targ_lang.word_index)+1dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)
dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
example_input_batch, example_target_batch = next(iter(dataset))
example_input_batch.shape, example_target_batch.shapeclass Encoder(tf.keras.Model):def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):super(Encoder, self).__init__()self.batch_sz = batch_szself.enc_units = enc_unitsself.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)self.gru = tf.keras.layers.GRU(self.enc_units,return_sequences=True,return_state=True,recurrent_initializer='glorot_uniform')def call(self, x, hidden):x = self.embedding(x)output, state = self.gru(x, initial_state = hidden)return output, statedef initialize_hidden_state(self):return tf.zeros((self.batch_sz, self.enc_units))class BahdanauAttention(tf.keras.layers.Layer):def __init__(self, units):super(BahdanauAttention, self).__init__()self.W1 = tf.keras.layers.Dense(units)self.W2 = tf.keras.layers.Dense(units)self.V  = tf.keras.layers.Dense(1)def call(self, query, values):hidden_with_time_axis = tf.expand_dims(query, 1)score = self.V(tf.nn.tanh(self.W1(values) + self.W2(hidden_with_time_axis)))attention_weights = tf.nn.softmax(score, axis=1)context_vector = attention_weights * valuescontext_vector = tf.reduce_sum(context_vector, axis=1)return context_vector, attention_weightsclass Decoder(tf.keras.Model):def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):super(Decoder, self).__init__()self.batch_sz = batch_szself.dec_units = dec_unitsself.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)self.gru = tf.keras.layers.GRU(self.dec_units,return_sequences=True,return_state=True,recurrent_initializer='glorot_uniform')self.fc = tf.keras.layers.Dense(vocab_size)self.attention = BahdanauAttention(self.dec_units)   # 使用注意力def call(self, x, hidden, enc_output):context_vector, attention_weights = self.attention(hidden, enc_output)x = self.embedding(x)x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)output, state = self.gru(x)output = tf.reshape(output, (-1, output.shape[2]))x = self.fc(output)return x, state, attention_weightsdef loss_function(real, pred):mask   = tf.math.logical_not(tf.math.equal(real, 0))loss_  = loss_object(real, pred)mask   = tf.cast(mask, dtype=loss_.dtype)loss_ *= maskreturn tf.reduce_mean(loss_)@tf.function   # 装饰器来将python代码转成图表示代码
def train_step(inp, targ, enc_hidden):loss = 0with tf.GradientTape() as tape:enc_output, enc_hidden = encoder(inp, enc_hidden)dec_hidden = enc_hiddendec_input = tf.expand_dims([targ_lang.word_index['<start>']] * BATCH_SIZE, 1)for t in range(1, targ.shape[1]):predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)loss += loss_function(targ[:, t], predictions)dec_input = tf.expand_dims(targ[:, t], 1)batch_loss = (loss / int(targ.shape[1]))variables = encoder.trainable_variables + decoder.trainable_variablesgradients = tape.gradient(loss, variables)optimizer.apply_gradients(zip(gradients, variables))return batch_lossdef evaluate(sentence):attention_plot = np.zeros((max_length_targ, max_length_inp))sentence = preprocess_sentence(sentence)inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],maxlen=max_length_inp,padding='post')inputs = tf.convert_to_tensor(inputs)result = ''hidden = [tf.zeros((1, units))]enc_out, enc_hidden = encoder(inputs, hidden)dec_hidden = enc_hiddendec_input = tf.expand_dims([targ_lang.word_index['<start>']], 0)for t in range(max_length_targ):predictions, dec_hidden, attention_weights = decoder(dec_input,dec_hidden,enc_out)attention_weights = tf.reshape(attention_weights, (-1, ))attention_plot[t] = attention_weights.numpy()predicted_id = tf.argmax(predictions[0]).numpy()result += targ_lang.index_word[predicted_id] + ' 'if targ_lang.index_word[predicted_id] == '<end>':return result, sentence, attention_plotdec_input = tf.expand_dims([predicted_id], 0)return result, sentence, attention_plotdef plot_attention(attention, sentence, predicted_sentence):fig = plt.figure(figsize=(10,10))ax = fig.add_subplot(1, 1, 1)ax.matshow(attention, cmap='viridis')fontdict = {'fontsize': 14}ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)ax.xaxis.set_major_locator(ticker.MultipleLocator(1))ax.yaxis.set_major_locator(ticker.MultipleLocator(1))plt.show()def translate(sentence):result, sentence, attention_plot = evaluate(sentence)print('原文:%s' % (sentence))print('译文:{}'.format(result))attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]plot_attention(attention_plot, sentence.split(' '), result.split(' '))# restoring the latest checkpoint in checkpoint_direncoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)
sample_hidden = encoder.initialize_hidden_state()
sample_output, sample_hidden = encoder(example_input_batch, sample_hidden)
print ('编码器输出结构: (批大小, 序列长度, 单元) {}'.format(sample_output.shape))
print ('编码器隐藏层状态结构: (批大小, 单元) {}'.format(sample_hidden.shape))attention_layer = BahdanauAttention(10)
attention_result, attention_weights = attention_layer(sample_hidden, sample_output)
print("注意力结果结构:(批大小,单元) {}".format(attention_result.shape))
print("注意力权重结构:(批大小,序列长度, 1) {}".format(attention_weights.shape))decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)
sample_decoder_output, _, _ = decoder(tf.random.uniform((64, 1)),sample_hidden, sample_output)
print ('解码器输出结构: (批大小, 词汇大小) {}'.format(sample_decoder_output.shape))optimizer = tf.keras.optimizers.Adam()
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction='none')checkpoint_dir   = './machinetranslation.checkpoints'
checkpoint_prefix= os.path.join(checkpoint_dir, "ckpt")
checkpoint       = tf.train.Checkpoint(optimizer=optimizer,encoder=encoder,decoder=decoder)
checkpointmanager= tf.train.CheckpointManager(checkpoint, directory=checkpoint_dir, checkpoint_name='ckpt', max_to_keep=1)if os.listdir(checkpoint_dir):print("--------------------加载已训练模型--------------------")checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))TrainYES=False
time.sleep(60)
STRpredicted=""
INTinitloss=100
epoch=0
while True:if not TrainYES:os.system("clear")print("机器翻译:西班牙文 <<<--->>> 英文")print("        Train..............训练数据",STRpredicted)print("        Translate..........翻译语句")print("        Quit...............退出系统")STRinput=input("        >>>>>>>>请输入选择项:")STRinput=STRinput.upper()                                                   # 将输入项转换为大写if STRinput=="TRAIN":STRstarttime=">>>>>>>>>>本轮训练开始时间:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(STRstarttime)start = time.time()enc_hidden = encoder.initialize_hidden_state()total_loss = 0for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)):batch_loss = train_step(inp, targ, enc_hidden)total_loss += batch_lossif batch % 10 == 0:print('训练轮次:{:>4d},批次:{:>10d},损失率:{:.10f}'.format(epoch + 1,batch,batch_loss.numpy()))if total_loss / steps_per_epoch < INTinitloss:INTinitloss=total_loss / steps_per_epochcheckpointmanager.save()### checkpoint.save(file_prefix = checkpoint_prefix)STRendtime="<<<<<<<<<<本轮训练结束时间:"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print(STRendtime)print('训练轮次:{:>4d},损失率:{:.10f},耗时:{:.10f}秒\n'.format(epoch + 1, total_loss / steps_per_epoch, time.time() - start ))STRpredicted=".....训练轮次:"+str(epoch + 1)+",损失率:"+str(total_loss / steps_per_epoch)+",耗时:"+str(time.time() - start)+"秒"epoch+=1if epoch < 5:TrainYES=Trueelse:TrainYES=Falseelif STRinput=="TRANS" or STRinput=="TRANSLATE":if os.listdir(checkpoint_dir):print("--------------------加载已训练模型--------------------")checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))while True:print("输入样例:hace mucho frio aqui. esta es mi vida. ?todavia estan en casa?")STRinput1=input("请输入待翻译语句(Exit返回):")if STRinput1.upper()=="EXIT" or STRinput1.upper()=="E":breakelif len(STRinput1)==0:STRinput1=u'hace mucho frio aqui. esta es mi vida. ?todavia estan en casa?'else:STRinput1=u"'"+STRinput1+"'"translate(STRinput1)elif STRinput=="QUIT" or STRinput=="Q":breakelse:continue

机器翻译:西班牙文「---」英文相关推荐

  1. 没有会员wps合并多个sheet_WPS「合并文档」功能,如何“唰”一下把多个文档合并到一起?...

    在我们的日常工作中,合并多个文档时,多数是将各文档逐一打开.复制.粘贴.关闭等,既麻烦又耗时,还会影响完成进度.那么有没有什么"骚"操作,可以快速高效合并文档?今天就给大家分享如何 ...

  2. VS2015支持UTF-8 with BOM编码格式处理中文、西班牙文、法文等非英文字符

    Detail: 在使用VS2015编译ImageMagicK库时,由于其中源码文件带有非英文字符串,导致VS编译出错. LANGUAGE(bn /* Bengali */,GLASS,"আম ...

  3. 「石墨文档」在线协同办公系统平台免费在线办公文档兼容Office

    武汉初心科技有限公司成立于2014年,在北京.上海.武汉设有分支机构和服务中心,自推出中国第一款在线协同文档办公软件--「石墨文档」以来始终保持业界领先地位,现已成为国内体系最完整.功能最完备的企业级 ...

  4. 「弟子入則孝,出則弟,謹而信,泛愛眾,而親仁,行有餘力,則以學文。」...

    「弟子入則孝,出則弟,謹而信,泛愛眾,而親仁,行有餘力,則以學文.」 語出春秋時期孔子的<論語·學而篇>-- 子曰:「道千乘之國,敬事而信,節用而愛人,使民以時.」 子曰:「弟子入則孝,出 ...

  5. 为什么日本人打电话时,要先说「もしもし」?

    一 这个说法居然在绳文•弥生时期(距今约2000年前)就有了.在绳文时期,一到晚上,人们就只能靠月光或者火把照明,外面是一片漆黑.谁要是因为什么事不得不去森林.或是其他没什么人住的地方,就会很害怕.据 ...

  6. Python 调用有道翻译api接口翻译外文网站的整篇西班牙文实战演示

    Python 调用有道翻译 api 接口翻译整篇西班牙文实战演示 第一章:翻译效果展示 ① 翻译文章示例一[阿尔卡拉门的无海摩纳哥:"不到4万欧元,你就不能在这里租任何东西."] ...

  7. simplexml php,PHP 使用 SimpleXML 遇到冒号「:」的解法

    PHP 使用 SimpleXML 来解析 XML 很方便,解析 RSS 也是轻松愉快,不过要解析 WordPress 的 RSS 时,遇到 XML Tag 的名称有「:」,造成解析不到,要怎么解决呢? ...

  8. 「あるいは」 「もしくは」 「または」 「それとも」的区别

    「もしくは」:若しくは (接続詞)二つの中からどちらか一つを選択する. 私鉄-地下鉄が便利です/私营铁路列车或者地铁方便. お申し込みは電話-ファックスでどうぞ/报名请用电话或传真. 「あるいは」:或 ...

  9. 日语学习  「そっと」 和 「こっそり」 的区別

    http://blog.hjenglish.com/seton/archive/2010/11/22/1648666.html 「そっと」は人に迷惑をかけずに?远虑しながらといったニュアンスがあり. ...

最新文章

  1. 中间件业务在网易轻舟容器平台的性能调优实践
  2. SQL------Hint
  3. 网页设计上机考试原题_全国计算机三级信息安全考试 经验分享
  4. electerm,免费开源的SSH桌面终端,像xshell、termius一样好用
  5. python学习笔记全过程_Python学习笔记一(Hello World)
  6. sencha touch 类的使用
  7. python模型预测_《Python机器学习——预测分析核心算法》——1.5 构建预测模型的流程...
  8. 百度硬盘搜索使用指南
  9. 算法分析与设计实验报告——实现哈夫曼编码
  10. 海康大华网络录像机摄像机设备几种NTP校时方法
  11. 数据分析——RFM模型
  12. 计算机网络网线制作与测试结果,网线制作和测试
  13. 遥感中的数字量化值DN, 辐射亮度Radiance, 反射率Reflectance,发射率Emissive的意义
  14. linux下通过ping命令监控网络抖动脚本
  15. 机器人笔记psv中文_《机器人笔记》白金攻略 机器人笔记奖杯攻略
  16. html网页不随缩放而变形,html不随放大缩小而变形——initial-scale
  17. Vulkan_Shader_Day01—光照(物体颜色)
  18. 无人驾驶及Apollo开源平台技术教程
  19. 年薪30万只是中游水平,算法工程师是一种怎样的存在?
  20. IPsec中IKE与ISAKMP过程分析(快速模式-消息1)

热门文章

  1. python文本框焦点设置_如何在tkinter输入框中设置焦点
  2. DZY Loves Modification
  3. C语言学堂在线测试题防丢失汇总
  4. centos6.6下安装moxa多串口卡(cp-168u v2.1)
  5. 中国计算机系统集成行业需求现状与市场投资风险建议报告2021~2027年
  6. 视频教程-征服Node.js 7.x视频课程(5):使用Buffer处理二进制数据-Node.js
  7. PSP - AlphaFold2 适配不同来源搜索的 MSA 接口
  8. 1e6在C语言,热电偶转换C语言程序
  9. 如何从电脑远程访问 iPhone?
  10. 麒麟linux怎么安装软件,在优麒麟Ubuntu Kylin 20.04下安装QQ for Linux的方法