Determine if string exists in file

前端 未结 2 1669
长情又很酷
长情又很酷 2021-01-28 22:35

I have a list of strings such as:

John

John Doe

Peter Pan

in a .txt file.

I want to make a loop that checks if a ce

相关标签:
2条回答
  • 2021-01-28 23:00

    If you want to check for multiple names use a trie. If you have just one name, you can use KMP.

    I'll explain this for multiple names you want to check that exist, since for only one, the example provided on Wikipedia is more than sufficient and you can apply the same idea.

    Construct the said trie from your names you want to find, and for each line in file, traverse the trie character by character until you hit a final node.

    BONUS: trie is used by Aho-Corasick algorithm, which is an extension of KMP to multiple patters. Read about it. It's very worthwhile.

    UPDATE:

    For checking if a single name exists, hash the name you want to find, then read the text file line by line. For each line, hash it with the same function and compare it to the one you want to find. If they are equal, compare the strings character by character. You need to do this to avoid false positives (see hash collisions)

    0 讨论(0)
  • 2021-01-28 23:06

    Ha ha, ep0's answer is very sophisticated!

    However, you want to use a parsing loop something like this (this example expects that your names are separated by carriage returns). Consider that you have a text file with contents arranged like this:

    John
    Harry
    Bob
    Joe
    

    Here is your script:

    fileread, thistext, %whatfile%  ;get the text from the file into a variable
    ;Now, loop through each line and see if it matches your results:
    
    loop, parse, thistext, `r`n, `r`n
    {
      if(a_loopfield = "John")
         msgbox, Hey! It's John!
      else
         msgbox, No, it's %a_loopfield%
    }
    

    If your names are arranged in a different order, you might have to either change the delimiter for the parsing loop, or use regex instead of just a simple comparison.

    0 讨论(0)
提交回复
热议问题