Create New Variables - Translate Text
(Redirected from Create New Variables - Translate)
Translate text in the selected variable(s) into another language using Google Cloud Translation
This QScript translates text questions to another language and saves the translated text as new questions. The user is prompted for the text questions to translate, as well as the source and output languages. A variable may be supplied by the user containing the source language for each case. Translation is done by Google Cloud Translation.
Example
The table below shows the original Chinese text in the first column and the English translation in the second column:
How to apply this QScript
- Start typing the name of the QScript into the Search features and data box in the top right of the Q window.
- Click on the QScript when it appears in the QScripts and Rules section of the search results.
OR
- Select Automate > Browse Online Library.
- Select this QScript from the list.
Customizing the QScript
This QScript is written in JavaScript and can be customized by copying and modifying the JavaScript.
Customizing QScripts in Q4.11 and more recent versions
- Start typing the name of the QScript into the Search features and data box in the top right of the Q window.
- Hover your mouse over the QScript when it appears in the QScripts and Rules section of the search results.
- Press Edit a Copy (bottom-left corner of the preview).
- Modify the JavaScript (see QScripts for more detail on this).
- Either:
- Run the QScript, by pressing the blue triangle button.
- Save the QScript and run it at a later time, using Automate > Run QScript (Macro) from File.
Customizing QScripts in older versions
JavaScript
includeWeb("QScript Utility Functions");
includeWeb("QScript Selection Functions");
includeWeb("QScript Functions to Generate Outputs");
includeWeb("QScript R Output Functions");
var languages = ["Afrikaans","Albanian","Amharic","Arabic","Armenian","Azerbaijani","Basque",
"Belarusian","Bengali","Bosnian","Bulgarian","Catalan","Cebuano","Chichewa",
"Chinese (Simplified)","Chinese (Traditional)","Corsican","Croatian","Czech",
"Danish","Dutch","English","Esperanto","Estonian","Filipino","Finnish","French",
"Frisian","Galician","Georgian","German","Greek","Gujarati","Haitian Creole",
"Hausa","Hawaiian","Hebrew","Hindi","Hmong","Hungarian","Icelandic","Igbo",
"Indonesian","Irish","Italian","Japanese","Javanese","Kannada","Kazakh","Khmer",
"Kinyarwanda","Korean","Kurdish (Kurmanji)","Kyrgyz","Lao","Latin","Latvian",
"Lithuanian","Luxembourgish","Macedonian","Malagasy","Malay","Malayalam","Maltese",
"Maori","Marathi","Mongolian","Myanmar (Burmese)","Nepali","Norwegian",
"Odia (Oriya)","Pashto","Persian","Polish","Portuguese","Punjabi","Romanian",
"Russian","Samoan","Scots Gaelic","Serbian","Sesotho","Shona","Sindhi","Sinhala",
"Slovak","Slovenian","Somali","Spanish","Sundanese","Swahili","Swedish","Tajik",
"Tamil","Tatar","Telugu","Thai","Turkish","Turkmen","Ukrainian","Urdu","Uyghur",
"Uzbek","Vietnamese","Welsh","Xhosa","Yiddish","Yoruba","Zulu"];
function getVariableOrQuestionLabel(variable) {
if(/- Multi/.test(variable.question.variableSetStructure)) {
return variable.question.name + " " + variable.label;
} else {
return variable.label;
}
}
translateText();
function translateText() {
const allowed_types = ["Text", "Text - Multi"];
let selected_questions = selectInputQuestions(allowed_types);
if (!selected_questions)
return false;
let data_file = getDataFileFromQuestions(selected_questions);
// Prompt user for source language
let source_index = selectOne('Select the source language', ["English", "Specify with variable"].concat(languages), null, 0);
let source_language, var_name;
if (source_index === 0)
source_language = "'English'";
else if (source_index === 1)
{
let candidate_variables = getVariables(data_file.questions);
let source_language_var = selectOneVariableByNameAndLabel("Select the source language variable", candidate_variables, false);
var_name = source_language_var.name;
source_language = checkDuplicateVariable(var_name) ? generateDisambiguatedVariableName(source_language_var) : stringToRName(var_name);
}
else
source_language = "'" + languages[source_index - 2] + "'";
// Prompt user for output language
var output_index = selectOne('Select the output language (translated by Google Cloud Translation)', ["English"].concat(languages), null, 0);
if (output_index === 0)
output_language = "'English'";
else
output_language = "'" + languages[output_index - 1] + "'";
if (source_language == output_language)
{
log("The source language is the same as the output language. No translation has been performed.");
return false;
}
let new_r_questions = [];
const structure_name = inDisplayr() ? "variable set" : "question";
for (var i = 0; i < selected_questions.length; i++)
{
let question = selected_questions[i];
let variables = question.variables;
let last_variable = getLastVariable(variables);
let new_question_name = preventDuplicateQuestionName(question.dataFile, output_language.replace(/'/g, "") + " translation of " + question.name);
let temp_var_name = randomVariableName(16); // temporary name, random to (almost) guarantee uniqueness
// Generate expression
let expression;
if (variables.length === 1) {
let var_name = variables[0].name;
let expr_name = checkDuplicateVariable(var_name) ? generateDisambiguatedVariableName(variables[0]) : stringToRName(var_name);
let r_name = "variable";
expression = r_name + " <- " + expr_name + "\n" +
"flipTextAnalysis::Translate(" + r_name + ", " + source_language + ", " + output_language + ")\n";
} else {
let variable_labels = variables.map(function(x) {return(getVariableOrQuestionLabel(x))});
let expr_names = variables.map(function(v){
return checkDuplicateVariable(v.name) ? generateDisambiguatedVariableName(v) : stringToRName(v.name);
});
let expr_name = [];
for (let i = 0; i < variables.length; i += 1) {
expr_name[i] = stringToRName(variable_labels[i]) + " = " + expr_names[i];
}
let r_name = structure_name.replace(" ", ".").slice(0, -1);
let expr_prefix = r_name + ' <- data.frame(';
let white_space = " ".repeat(expr_prefix.length);
expression = expr_prefix + expr_name.join(",\n" + white_space) + ',\n' +
white_space + 'check.names = FALSE, stringsAsFactors = FALSE)\n' +
"apply(" + r_name + ", 2, flipTextAnalysis::Translate," + source_language + ", " + output_language + ")\n";
}
// Run expression to create R question
let new_r_question;
try {
new_r_question = data_file.newRQuestion(expression, new_question_name, temp_var_name, last_variable);
if (variables.length === 1)
new_r_question.questionType = "Text";
else
new_r_question.questionType = "Text - Multi";
insertAtHoverButtonIfShown(new_r_question);
}
catch (e) {
log("The translation could not be performed for this " + structure_name + " : " + e);
return false;
}
// Replace temporary variable names
nameSequentialVariables(new_r_question.variables, "translated");
new_r_questions.push(new_r_question);
}
reportNewRQuestion(new_r_questions, "Translated question(s)");
return true;
}
See also
- QScript for more general information about QScripts.
- QScript Examples Library for other examples.
- Online JavaScript Libraries for the libraries of functions that can be used when writing QScripts.
- QScript Reference for information about how QScript can manipulate the different elements of a project.
- JavaScript for information about the JavaScript programming language.
- Table JavaScript and Plot JavaScript for tools for using JavaScript to modify the appearance of tables and charts.
Displayr - Anything Menu
Displayr - Insert
Displayr - New Variable Menu
Extensions
Q Technical Reference
Q Technical Reference
Q Technical Reference
Q Technical Reference
Q Technical Reference > Setting Up Data > Creating New Variables
Q Technical Reference > Setting Up Data > Creating New Variables
Q Technical Reference > Updating and Automation > Automation Online Library
Q Technical Reference > Updating and Automation > JavaScript > QScript > QScript Examples Library
Q Technical Reference > Updating and Automation > JavaScript > QScript > QScript Examples Library > QScript Online Library
User Interface > Transformation