首页 > 解决方案 > Save values into a list and send it to a function

问题描述

So I am trying to create a script where I loop through a text file where I want to be able to save all values from txt file and then send it into a function. I will explain it after the code below:

randomnames.txt

Alejandro  
Tisha  
Eleni  
Milton  
Jeanice  
Billye  
Vicki  
Shelba  
Valorie  
Penelope  
Mellissa  
Ambrose  
Retta  
Milissa  
Charline  
Brittny  
Ehtel  
Hilton  
Hobert  
Lakendra  
Silva  
Lawana  
Sidney  
Janeen  
Audrea  
Orpha  
Peggy  
Kay  
Marvis  
Tia  
Randy  
Cary  
Santana  
Roma  
Mandi  
Tyrone  
Felix  
Maybelle  
Leonia  
Micha  
Idalia  
Aleida  
Elfrieda  
Velia  
Cassondra  
Drucilla  
Oren  
Kristina  
Madison  
Dia  


names.txt

Alejandro
Tisha
Eleni
Dia
Hobert

import json, time, sys, os, timeit, random, colorama, requests, traceback, multiprocessing, re
from random import choice
import threading


def get_names():

    name_test = [line.rstrip('\n') for line in open('randomnames.txt')]
    return name_test

def filter(thread, i):

    text = thread

    positive_keywords = [i]

    has_good = False

    for ch in ['&', '#', '“', '”', '"', '*', '`', '*', '’', '-']:
        if ch in text:
            text = text.replace(ch, "")

    sentences = [text]

    def check_all(sentence, ws):
        return all(re.search(r'\b{}\b'.format(w), sentence) for w in ws)

    for sentence in sentences:
        if any(check_all(sentence, word.split('+')) for word in positive_keywords):
            has_good = True
            break

    if not has_good or i == "":
        sys.exit()

    print('Matched ' + text)

def main():
    old_list = []

    old_names_list = []

    while True:

        new_names_list = [line.rstrip('\n') for line in open('names.txt')]
        for new_thread in get_names():

            if not new_names_list == old_names_list:
                for i in new_names_list:
                    if not i in old_names_list:
                        threading.Thread(target=filter, args=(new_thread, i)).start()
                        if new_thread not in old_list:
                            old_list.append(new_thread)

            elif new_thread not in old_list:
                threading.Thread(target=filter, args=(new_thread, new_names_list)).start()
                old_list.append(new_thread)

        else:
            randomtime = random.randint(1, 3)
            print('No changes!')
            time.sleep(randomtime)

        old_names_list = new_names_list
if __name__ == '__main__':
    try:
        main()

    except KeyboardInterrupt:
        print('Keyboard - Interrupted' )
        sys.exit()

How the program works right now is that it checks all names in randomnames.txt and checks if any of these names matches names in names.txt. If there is a match it will print out there is a match, if not then it will just do sys.exit (Which kills the thread).

However my problem sits in the part of

if not new_names_list == old_names_list:
                    for i in new_names_list:
                        if not i in old_names_list:
                            threading.Thread(target=filter, args=(new_thread, i)).start()
                            if new_thread not in old_list:
                                old_list.append(new_thread)

                elif new_thread not in old_list:
                    threading.Thread(target=filter, args=(new_thread, new_names_list)).start()
                    old_list.append(new_thread)

Where I believe the problem is where it runs alot of threads due it takes one name from names.txt and checks all names one by one (thread) names in randomnames.txt. Meaning if there is 50 names in the randomnames.txt it will create 50 threads where it checks if any of names from randomnames.txt matches the name from names.txt. If it matches then it will print out there is a match. The problem is it needed to create 50 threads of just one name and meaning it will add another 50 threads for following new name.

The reason I believe that is a problem and how it can be solved is that if maybe adding all names from names.txt into a list and then send it to filter() where it checks if any in names.txt matches the names from randomnames.txt

标签: pythonlistfor-loop

解决方案


原始帖子中的代码非常复杂。从根本上说,您正在比较两个名称集合以进行匹配。这是集合论,您应该使用 Python 集合来执行此操作,而不是列表。考虑:

names = {'Bob', 'Cindy', 'Dave'}
other_names = {'Lou', 'Pete', 'Cindy'}
print(names & other_names)  # {‘Cindy’}

推荐阅读