Use FirstPositioning[] multiple times to separate and organise an txt file?

Posted 6 months ago
716 Views
|
3 Replies
|
2 Total Likes
|
 Hi everyone, I am trying to separate and organise an txt file that I imported in Mathematica. I'd like to you the the function FirstPosition[list, keyword], this works until I want to use this function for the second/third/fourth etc time. Then mathematica just search for the first keyword and ignore the the following ones. I tried to use: FirstPositioning[list, key word1];FirstPositioning[list, key word2];FirstPositioning[list, key word3] etc... If I try this code without the used of the semicolon than mathematica gives me the correct position of keyword 1 but not for keyword 2/3/4.Short, what I want Mathematica to do is First search for keyword1, if found THAN look for keyword2 (from the position of keyword1) and so on. Is there anyone who can help me with this problem, Thanks!
3 Replies
Sort By:
Posted 6 months ago
 Kim,Is the txt coming in as a list of words? or is it a string of words. If it is a string of words then FirstPosition will not work. You need to use String searching instead of list searching.I'll assume you are using a list of words like this: wordlist = {"aaa", "bbb", "ccc", "bbb", "ddd", "eee", "fff", "ggg", "hhh", "fff", "iii"} The operation you describe is recursive -- you want to find a string starting at a word and search within that substring.First we find a substring with one key word (the keyword is in a list all by itself) finder[lst_, {lastone_}] := Drop[lst, First[FirstPosition[lst, lastone]]] Now overload the function to operate on the first keyword and recursively send the result to the function for the rest of the keywords: finder[lst_, toFind_List] := finder[finder[lst, {First[toFind]}], Rest[toFind]] Now we can use it: keywords = {"bbb", "ddd", "fff"}; finder[wordlist, keywords] To get {"ggg", "hhh", "fff", "iii"} We searched for the "bbb", then searched for the "ddd" in the remaining string, then searched for the "fff". To verify what is happening you can call finder sequentially: In[26]:= n1 = finder[wordlist, {"bbb"}] Out[26]= {"ccc", "bbb", "ddd", "eee", "fff", "ggg", "hhh", "fff", \ "iii"} In[27]:= n2 = finder[n1, {"ddd"}] Out[27]= {"eee", "fff", "ggg", "hhh", "fff", "iii"} In[28]:= n3 = finder[n2, {"fff"}] Out[28]= {"ggg", "hhh", "fff", "iii"} Regards,Neil*Edit: simplified the finder definition