因此,我尝试创建一个脚本,在其中循环遍历一个文本文件,以便能够保存txt文件中的所有值,然后将其发送到函数中。我将在下面的代码之后解释:
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()
这个程序现在的工作原理是将所有的名字都签入随机名称.txt并检查这些名字是否与名称.txt. 如果有一个匹配,它会打印出来有一个匹配,如果没有,那么它只会做系统出口(这会终止线程)。你知道吗
然而,我的问题在于
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)
我认为问题在于它运行了很多线程,因为它只使用了一个名称名称.txt并逐个(线程)检查中的所有名称随机名称.txt. 也就是说如果有50个名字随机名称.txt它将创建50个线程来检查随机名称.txt与中的名称匹配名称.txt. 如果它匹配,那么它会打印出来有一个匹配。问题是它需要创建50个只使用一个名称的线程,这意味着它将为后面的新名称添加另外50个线程。你知道吗
我认为这是一个问题,如何解决这个问题的原因是,如果把名称.txt然后将其发送到filter(),在那里它检查名称.txt匹配来自随机名称.txt你知道吗
原文中的代码过于复杂。基本上,您是在比较两个名称集合的匹配项。这是集合论,您应该使用Python集合来实现这一点,而不是列表。考虑:
相关问题 更多 >
编程相关推荐