Return a list of all strings in the file containing the searched string

Asked

Viewed 37 times

0

I am trying to make a method that scans a list (my list comes from an external file that uses readlines() to assemble a list of strings) and compares it to a string passed by parameter. The feedback for my test to work needs to be a Len(). I’ve tried it in many ways and the only way I could was this one, but I can only figure out how many characters there are on the list, one at a time and I can’t calculate a large character either. I’m literally stuck.

def buscar(self, string):
    arq = self.arquivo

    for linha in arq.readlines():
        novaLinha = []
        novaLinha.append(linha.rstrip())
        contTotal = 0

        for string in novaLinha:

            for p in string:
                cont = 0
                for w in string:
                     if w.startswith(p):
                         cont += 1

                     else:
                         cont = 0

                contTotal += cont
                print( p + ' aparece ' + str(cont) + ' vezes nas palavra ' + string)

This is the test I need you to pass.

    def test_01_buscar(self):
    arquivo = open('texto1.txt', 'r')
    sf = SearchFile(arquivo)
    self.assertEqual(len(sf.buscar('a')), 2)
    self.assertEqual(len(sf.buscar('b')), 1)
    self.assertEqual(len(sf.buscar('c')), 1)
    self.assertEqual(len(sf.buscar('z')), 0)
    self.assertEqual(len(sf.buscar('pinha')), 1)
  • 1

    "I cannot calculate a large character", what would be a "large character"? In fact, can you explain better what you want to do? Both the text and the code were a little confused to understand.

2 answers

0

def arquivo_ler(search):
   quantidade = 0
   arq = open('lista.txt', 'r')
   texto = arq.readlines()

   #ler cada linha do arquivo
   for linha in texto :
      palavras = linha.split(' ')
      palavras_f = []

      #ler cada plavra da lina
      for p in palavras:
         palavras_f.append(p.replace('\n',''))
      print(palavras_f)
      for p in palavras_f:
         if(p == search):
             quantidade+=1
   arq.close()
   return quantidade

This function solves your problem locates all occurrence of a searched word and returns the amount

  • I needed to return a list, however, I was able to still put a method Seek(0) in the for to return to the file in its initial position to read the line again, only then can resolve the return conflict have a list size to pass the test.

0


I managed to solve it this way, so my tests passed v:

    def buscar(self, string):
    lista = []
    texto = self.arquivo.readlines()

    for linha in texto:
        print(linha)
        if string in linha:
            lista.append(string)
    self.arquivo.seek(0)
    return lista

Browser other questions tagged

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