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

0

I'm 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 with a string passed by parameter. The return for my test run needs to be a len (). I have already tried in several ways and the only way I got was this one, however, I can only know the number of characters in the list, one at a time and also I can not calculate a large character. 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 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)
    
asked by anonymous 06.11.2018 / 19:20

2 answers

0

I was able to solve this, 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
    
06.11.2018 / 23:39
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 finds all occurrences of a searched word and returns the quantity

    
06.11.2018 / 21:31