文本中有\n,而响应中既有\n也有“实际换行”。print()输出时都会将其作为换行符处理

我有一些这样的Python函数:

def translate(text):    while True:        response = openai.ChatCompletion.create(            model="gpt-4",            messages=[                {"role": "system", "content": "You are a translator, you will receive English language sentences from a videogame needing localization. You must respect the punctuation and capitalization. You must maintain \n as is"},                {"role": "system", "content": "The target language is Spanish"},                {"role": "user", "content": text}            ],            temperature=0        )        return response.choices[0].message['content']

对于text输入参数,我有一个这样的字符串(实际上更长):

text_to_translate = """Blocks melee and\n ranged units' line of sight.Sink the unit. Sunken\n units are more vulnerable to enemy attacks.Teleport the unit through\n this portal to an exit portal."""

对于响应,我这样做:

translated_text = translate(text_to_translate)print(translated_text, flush=True)

问题是,print()会处理\n并(正确地)在输出中插入换行符,如下所示:

Bloquea la línea de visión deunidades de combate cuerpo a cuerpo y a distancia.Hunde la unidad. Las unidadeshundidas son más vulnerables a los ataques enemigos.Teletransporta la unidad a travésde este portal a un portal de salida.

如何让\n保持不变,而三引号字符串中的实际换行符得到尊重呢?


回答:

字符串字面量(无论使用什么引号)与str值是不一样的。字面量包含\n二元组;它创建的str值包含U+000a。

>>> x = """foo\nbar...baz""">>> len(x)11  # 不是12>>> x'foo\nbar\nbaz'  # 字符串的字符串表示使用二元组>>> print(x)  # U+000a被渲染为换行符和回车符foobarbaz

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注