5
$\begingroup$

I have the following list:

l={"ALMONDBEAN", "ALMONDMILK", "ALMONDOLIVE_OIL", "ALMONDORANGE_PEEL", 
"ALMONDVANILLA", "ALMONDWHEAT", "ALMONDWHISKEY", "ANISECUCUMBER",
"ANISELEMON", "APPLEAPPLE_BRANDY", "APPLEBLACK_CURRANT",
"APPLECHERRY", "AVOCADOMILK"}

I want to modify it to have the following:

l={"Food.ALMOND.ALMONDBEAN", "Food.ALMOND.ALMONDMILK", "Food.ALMOND.ALMONDOLIVE_OIL", "Food.ALMOND.ALMONDORANGE_PEEL", 
    "Food.ALMOND.ALMONDVANILLA", "Food.ALMOND.ALMONDWHEAT", "Food.ALMOND.ALMONDWHISKEY", "Food.ANISE.ANISECUCUMBER",
    "Food.ANISE.ANISELEMON", "Food.APPLE.APPLEAPPLE_BRANDY", "Food.APPLE.APPLEBLACK_CURRANT",
    "Food.AVOCADO.APPLECHERRY", "Food.AVOCADO.AVOCADOMILK"}

Two things happen in this process: 1. "Food." shall be added to the beginning of each entry, 2. The first word of each entry shall be added to the middle. For example when we have "ALMONDBEAN" we want to get "ALMOND." and eventually have "Food.ALMOND.ALMONDBEAN"

$\endgroup$
8
$\begingroup$
ClearAll[reArrange]
reArrange[s_String] := ## & @@ StringCases[s, 
   StartOfString ~~ w__ ~~ rest__ ~~ EndOfString /; 
     (And @@ DictionaryWordQ /@ {w, ## & @@ StringSplit[rest, "_"]}) :> 
       StringRiffle[{"Food", w, s}, "."]]

reArrange /@ l

{"Food.ALMOND.ALMONDBEAN", "Food.ALMOND.ALMONDMILK", "Food.ALMOND.ALMONDOLIVE_OIL", "Food.ALMOND.ALMONDORANGE_PEEL", "Food.ALMOND.ALMONDVANILLA", "Food.ALMOND.ALMONDWHEAT", "Food.ALMOND.ALMONDWHISKEY", "Food.ANISE.ANISECUCUMBER", "Food.ANISE.ANISELEMON", "Food.APPLE.APPLEAPPLE_BRANDY", "Food.APPLE.APPLEBLACK_CURRANT", "Food.APPLE.APPLECHERRY", "Food.AVOCADO.AVOCADOMILK"}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.