0
|
9100 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
GROUPS:

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

Posted 10 years ago
 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 10 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 10 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?
Posted 10 years ago
 I find it difficult to understand exactly what you mean by that. The best way is to actually post Mathematica code in code blocks, and to attach data or notebook files as needed. Information on how to do all of this can be found here: How to post
Posted 10 years ago
 You might use FullForm to inspect the contents of what you Import from Excel. I have seen in the past things coming from Excel are sometimes quoted strings. Mathematica almost always hides the quotes, thinking that it what you would want it to do. So they may already be strings, possibly even nested inside several layers of { }. Perhaps FullForm can most easily tell you.