How to make a nested FOR?

Asked

Viewed 1,443 times

1

I’m opening two files, one is a text, and the other is a list. I want through nested check how many times each item in the list appears in the text.

I did so:

arquivo = open('texto.txt', 'r')
lista = open('lista.txt', 'r')

for item in lista:
   i = 0;
   for linha in arquivo:
      if item[0:-1] in linha:
    i += 1
    print(item)
    print(i)

Only that way he’s only showing the first item on the list and how many times he shows up. For example, if you have the word 'iPhone 6' in my list and it appears 3 times in the text, it gives that output:

iPhone 6
1
iPhone 6
2
iPhone 6
3 

2 answers

2

lista = ['iPhone 6', 'Apple', 'Android','Samsung']
text = '''
iPhone 6 é um dispostivo da Apple.
iPhone 6 não é da Samsung, iPonhe 6 é da Apple
'''

for l in lista:
    print (l,':',text.count(l))

iPhone 6 : 2
Apple : 2
Android : 0
Samsung : 1

1

You need to take the print that displays the value of the first loop from within the second:

for item in lista:
   i = 0;
   print(item)
   for linha in arquivo:
       if item[0:-1] in linha:
          i += 1
       print(i)

So it will display the first loop item once and then all the second loop items:

iPhone 6
1
2
3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.