Заменить слово в предложении на основе объекта, сделанного из массивов - PullRequest
0 голосов
/ 22 июня 2019

У меня есть ингредиенты объект, полученный из API. Я хочу заменить единиц в каждом из ингредиентов его аббревиатурой. Я пытаюсь сделать это с помощью объекта с именем units и использую значения, которые нужно заменить в массивах, но я даже не близок, чтобы заставить его работать.

Я пробовал это разными способами, это моя последняя попытка:

parseIngredient() {
    const ingredients = [
      "1 fresh ham, about 18 pounds, prepared by your butcher (See Step 1)",
      "7 cloves garlic, minced",
      "1 tablespoon caraway seeds, crushed",
      "4 teaspoons salt",
      "Freshly ground pepper to taste",
      "1 teaspoon olive oil",
      "1 medium onion, peeled and chopped",
      "3 cups sourdough rye bread, cut into 1/2-inch cubes",
      "1 1/4 cups coarsely chopped pitted prunes",
      "1 1/4 cups coarsely chopped dried apricots",
      "1 large tart apple, peeled, cored and cut into 1/2-inch cubes",
      "2 teaspoons chopped fresh rosemary",
      "1 egg, lightly beaten",
      "1 cup chicken broth, homemade or low-sodium canned"
    ];

    const units = {
      tbsp: ['tablespoons', 'tablespoon', 'tbsps', 'tbsp'],
      tsp: ['teaspoons', 'teaspoon', 'tsps', 'tsp'],
      cup: ['cups', 'cup'],
      oz: ['ounces', 'ounce'],
      pt: ['pints', 'pint', 'pt'],
      gal: ['gallons', 'gallon', 'gals', 'gal'],
      pound: ['pounds', 'pound', 'lbs', 'lb'],
      qt: ['quarts', 'quart', 'qts', 'qt'],
      l: ['liters', 'liter', 'l'],
      ml: ['mililiters', 'mililiter', 'mls', 'ml'],
      cl: ['centiliters', 'centiliter', 'cls', 'cl'],
      kg: ['kilograms', 'kilogram', 'kgs', 'kg'],
      g: ['grams', 'gram', 'gs', 'g'],
      mg: ['miligrams', 'miligram', 'mgs', 'mg'],
      inch: ['inches', 'inch', 'in']
    };

    const changedIngredients = ingredients.map(el => {
        let ing = el.toLowerCase();
        const keys = Object.keys(units);
        const values = Object.values(units);

        values.forEach((value, i) => {
            for (let j; j <= value.length; j++) {
                ing = ing.replace(value[j], keys[i]);
            }
        });
    });
}

Я ожидаю, что результат "4 teaspoons salt" будет, например, "4 tbsp salt".

Ответы [ 2 ]

0 голосов
/ 22 июня 2019

Вот код для желаемого выхода

// Polyfill of Contains method On String
if(!('contains' in String.prototype)) {
       String.prototype.contains = function(str, startIndex) {
                return -1 !== String.prototype.indexOf.call(this, str, startIndex);
       };
 }

function parseIngredient() {
  const ingredients = [
  "1 fresh ham, about 18 pounds, prepared by your butcher (See Step1)",
  "7 cloves garlic, minced",
  "1 tablespoon caraway seeds, crushed",
  "4 teaspoons salt",
  "Freshly ground pepper to taste",
  "1 teaspoon olive oil",
  "1 medium onion, peeled and chopped",
  "3 cups sourdough rye bread, cut into 1/2-inch cubes",
  "1 1/4 cups coarsely chopped pitted prunes",
  "1 1/4 cups coarsely chopped dried apricots",
  "1 large tart apple, peeled, cored and cut into 1/2-inch cubes",
  "2 teaspoons chopped fresh rosemary",
  "1 egg, lightly beaten",
  "1 cup chicken broth, homemade or low-sodium canned"
]
const units = {
  tbsp: ['tablespoons', 'tablespoon', 'tbsps', 'tbsp'],
  tsp: ['teaspoons', 'teaspoon', 'tsps', 'tsp'],
  cup: ['cups', 'cup'],
  oz: ['ounces', 'ounce'],
  pt: ['pints', 'pint', 'pt'],
  gal: ['gallons', 'gallon', 'gals', 'gal'],
  pound: ['pounds', 'pound', 'lbs', 'lb'],
  qt: ['quarts', 'quart', 'qts', 'qt'],
  l: ['liters', 'liter', 'l'],
  ml: ['mililiters', 'mililiter', 'mls', 'ml'],
  cl: ['centiliters', 'centiliter', 'cls', 'cl'],
  kg: ['kilograms', 'kilogram', 'kgs', 'kg'],
  g: ['grams', 'gram', 'gs', 'g'],
  mg: ['miligrams', 'miligram', 'mgs', 'mg'],
  inch: ['inches', 'inch', 'in']
};
const changedIngredients = ingredients.map(el => {
  let ing = el.toLowerCase();
  let shortHandedOutput=[];
  for(var prop in units){
     units[prop].map(u => {
      if(ing.contains(u)){ // Finds if the entry is in units
        ing = ing.replace(u,prop);
      }
   })
  }
  return ing;
});
}
// Execute Function
parseIngredient();
0 голосов
/ 22 июня 2019

Поддерживая свою структуру данных, вы можете сначала сгенерировать массив пар из объекта units, где каждая пара состоит из замены и регулярного выражения, используемого для этой замены.Для генерации этого массива пар мы можем использовать Object.entries () на объекте units в сочетании с Array.map () .Обратите внимание, что регистронезависимая функция добавлена ​​к регулярному выражению с флагом i.Также при создании регулярного выражения мы используем границы слов (\ b) , чтобы соответствовать целым словам, а не частям других слов (например, in внутри minced).Краткое изложение этого можно увидеть по следующей логике:

const replacements = Object.entries(units).map(([k, v]) =>
{
    v = v.map(s => `\\b${s}\\b`).join("|");
    return [k, new RegExp(v, "i")];
});

Наконец, вы можете .map() ингредиенты , как вы уже делали, применяя соответствующие замены к каждому элементумассив.

const changedIngredients = ingredients.map(el =>
{
    replacements.forEach(([unit, regexp]) => el = el.replace(regexp, unit));        
    return el;
});

Полный пример:

const ingredients = [
  "1 fresh ham, about 18 pounds, prepared by your butcher (See Step 1)",
  "7 cloves garlic, minced",
  "1 tablespoon caraway seeds, crushed",
  "4 teaspoons salt",
  "Freshly ground pepper to taste",
  "1 teaspoon olive oil",
  "1 medium onion, peeled and chopped",
  "3 cups sourdough rye bread, cut into 1/2-inch cubes",
  "1 1/4 cups coarsely chopped pitted prunes",
  "1 1/4 cups coarsely chopped dried apricots",
  "1 large tart apple, peeled, cored and cut into 1/2-inch cubes",
  "2 teaspoons chopped fresh rosemary",
  "1 egg, lightly beaten",
  "1 cup chicken broth, homemade or low-sodium canned"
];

const units = {
  tbsp: ['tablespoons', 'tablespoon', 'tbsps', 'tbsp'],
  tsp: ['teaspoons', 'teaspoon', 'tsps', 'tsp'],
  cup: ['cups', 'cup'],
  oz: ['ounces', 'ounce'],
  pt: ['pints', 'pint', 'pt'],
  gal: ['gallons', 'gallon', 'gals', 'gal'],
  pound: ['pounds', 'pound', 'lbs', 'lb'],
  qt: ['quarts', 'quart', 'qts', 'qt'],
  l: ['liters', 'liter', 'l'],
  ml: ['mililiters', 'mililiter', 'mls', 'ml'],
  cl: ['centiliters', 'centiliter', 'cls', 'cl'],
  kg: ['kilograms', 'kilogram', 'kgs', 'kg'],
  g: ['grams', 'gram', 'gs', 'g'],
  mg: ['miligrams', 'miligram', 'mgs', 'mg'],
  inch: ['inches', 'inch', 'in']
};

const replacements = Object.entries(units).map(([k, v]) =>
{
    v = v.map(s => `\\b${s}\\b`).join("|");
    return [k, new RegExp(v, "i")];
});

const changedIngredients = ingredients.map(el =>
{
    replacements.forEach(([unit, regexp]) => el = el.replace(regexp, unit));        
    return el;
});

console.log(changedIngredients);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...