# Can someone help with string replacement rules for large replacements sets?

Posted 7 years ago
5731 Views
|
4 Replies
|
0 Total Likes
|
 I have a list of text strings and a list of {word, alias) data that I would like to use to modify the original text strings. I would like to avoid having to type in the "->" characters.
4 Replies
Sort By:
Posted 7 years ago
 If you look at In[1]:= FullForm[{"dog", "cat"}] you see Out[1]//FullForm= List["dog", "cat"] If you do the same with In[2]:= FullForm["dog" -> "cat"] you see Out[2]//FullForm= Rule["dog", "cat"] So if you could just change List into Rule you would be done. Looking at the help page for Apply shows it does exactly that. But you want to do this to lots of pairs in a list. Looking at the help page for Map shows it will do the same thing to every item in a list.Really understanding how to use this should give you a whole new level of skill and ability in Mathematica.Note: There are some shortcuts in Mathematica that will let you save a few keystrokes. Some of those use things like # and &. Those could be used to write this using a few less characters, but then you would need to learn how # and & work. The result should be the same. And you can learn that as needed. In[1]:= text = {"The frog ate the dog", "The cat bit the frog"}; pairs = {{"frog", "goat"}, {"dog", "hampster"}, {"cat", "pig"}}; changeListToRule[x_] := Apply[Rule, x]; rules = Map[changeListToRule, pairs] Out[3]= {"frog" -> "goat", "dog" -> "hampster", "cat" -> "pig"} In[4]:= StringReplace[text, rules] Out[4]= {"The goat ate the hampster", "The pig bit the goat"} 
Posted 7 years ago
 Bill Simpson gave me a great start on this problem;Bravo! There is one detail that I neglected in re the format of my 'alias' data and that is the data is in text format (imported from Excel) and not in quotes-delimited format. Is there a way to treat that too?