I have a code that seems to have a slight issue it reads the file... But the issue is it can not identify the words/letters this is what i mean extract('test.txt',('A','E','I','O','U'))
the test.txt
is a txt file and the ('A','E','I','O','U')
is the words i want to find.
my code:
def extract(file,find=()):
with open(str(file),'r') as file:
find = list(find)
read_file = file.readlines()
num1 = 0
num = num1-1
for vals in find:
num1 += 1
pass
for finds in read_file:
linef = str(finds)
main_obj = find[num]
if main_obj in linef:
print("Yay")
elif linef != main_obj:
print("NO")
else:
print("???")
pass
extract('test.txt',('A','E','I','O','U'))
What my output is:
NO
NO
NO
NO
Yay
This is the expected output:
Yay
Yay
Yay
Yay
Yay
inside test.txt
:
A
E
I
O
U
I'll just leave this here. If the end result is to compare each variable inside of find
to each line in file
then this should do the job:
def extract(file, find=()):
with open(file) as F:
contents = F.readlines()
for line in contents:
if any([i in line for i in find]):
print("Yay")
else:
print("NO")
extract("test.txt", ('A','E','I','O','U'))
In the code:
for finds in read_file:
linef = str(finds)
main_obj = find[num]
if main_obj in linef:
print("Yay")
elif linef != main_obj:
print("NO")
you never increment num
and hence are essentially always comparing find[-1]
with main_obj
. I guess you have to increment num
if there is a match or whatever your requirement is.
if main_obj in linef:
num += 1
print("Yay")
Either way, this would be the most down-to-earth correct way to do what you are required to:
for temp in find:
not_found = True
for finds in read_files:
if temp in finds:
not_found = False
print("Yay")
break
elif temp != finds:
not_found = True # elif is not needed TBH but just adding for clarity
if not_found:
print("NO")
You just need to update your logic and remove this code. because it will always return -1 index on every increment.
num1 = 0
num = num1-1
for vals in find:
num1 += 1
pass
Just use one variable and increment it accordingly.
def extract(file, find=()):
num = 0
with open(str(file), 'r') as file:
find = list(find)
print(find)
read_file = file.read().splitlines()
print(read_file)
for finds in read_file:
linef = str(finds)
main_obj = find[num]
num += 1
if main_obj in linef:
print("Yay")
elif linef != main_obj:
print("NO")
else:
print("???")
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.