Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do i efficiently test to see if a string from a list in a txt file is in another txt?

in the file called "admin list.txt" it has :

_Cignus_

_JustMix

_N3

_R3

_Skofy

_Surfers_

_Vxpe

0Da3s

0h_Roby

0hHaze

0hPqnos

And I want to see if another file called "latest logs.txt" with something like:

[21:11:29] [Client thread/INFO]: [CHAT] mhyra wants to fight!

[21:11:30] [Client thread/INFO]: [CHAT] ? SkyWars Solo ? Warmup started. You will be teleported in the next 10 seconds.

[21:11:33] [Client thread/FATAL]: Error executing task

[21:11:33] [Client thread/INFO]: [CHAT] _Cignus_ wants to fight!

Contains ANY of the strings from the "admin list" then it prints "ALERT" if a string from "admin list" is in the last 20 lines of "latest logs.txt"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How would I do that?

>Solution :

Start off by saving all of the lines from your "admin list.txt" file into a list where each line is a separate element. This way, you have a list of keywords you can iterate over and check for.

keywords = []
with open('admin_list.txt', 'r') as f:
    keywords = f.read().splitlines()

Next, you would need the last 20 lines of the "latest logs.txt". If your file is not GBs large, you can simply do:

logs = []
with open('latest_logs.txt', 'r') as f:
    lines = f.read().splitlines()
    logs = lines[-20:]

Lastly, simply check for the keywords in every line of your logs list:

for line in logs:
    for word in keywords:
        if word in line:
            print ("ALERT")

You can easily modify this to also print the line and the keyword along with the alert. You’ll be iterating over 20 character-capped lines (a video-game chat-log by the looks of it), and you’ll be checking for a dozen or two keywords. The runtime for this is quite low – despite the nested for-loop implementation. However, this solution falls apart if your logs file is very large.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading