I am working on a script and the script should read a text file and test to see if the specified letters(a,a,r,d,v,a,r,k) are on each line. Im having a problem as I am trying to check for 3 different a’s instead of just one. My code is below:
#Variables
advk = ['a','a','r','d','v','a','r','k']
textfile = []
number = 0
life = 0
for line in open('input.txt', 'rU'):
textfile.append(line.rstrip().lower())
while life == 0:
if all(word in textfile[number] for word in advk):
printed = number + 1
print ("Aardvark on line " + str(printed))
number+=1
if number == len(textfile):
life+=1
else:
number+=1
Everytime you want to count something in python, keep the Counter class in mind.
Given the input line
the Counter would look like these
and
for your list of letters to search.
We use a trick by simply substracting the two Counters
advl - Counter(line.lower())and check if the resulting Counter has no elements left.Other things to note:
You can use the with statement to ensure your file gets closed.
You can use enumerate instead counting the line numbers.