A Program for finding all files in a nested folder that contains a specific string : Ruby Vs Python

This program has a major method ‘search in file’ that accepts a folder path as a parameter. Next initialize whatever variables we want.

Ruby
Python

def search_in_file(folder_path)
      @file_array = Array.new
      files_has_string = Array.new
      erb_files_has_no_string = Array.new
      rb_files_has_no_string = Array.new
      unknown_files = Array.new
      iterate_through_dir(folder_path, @file_array)
      ———
      ———

import os
import re
file_array = []
def search_in_file(folder_path):
      files_has_string = []
      erb_files_no_string = []
      rb_files_no_string = []
      unknown_files = []
      iterate_through_dir(folder_path)
      ———
      ———

Then calls a method ‘iterate_through_dir’ which has two parameters in ruby and one in python, ‘folder path’ and instance variable ‘file_array’. In python we initialized a gobal variable ‘file_array’. But in ruby ‘@file_array’ is an instance variable. This method finds file paths of files included in the folder we have given, say ‘sample_folder’. Using the class method ‘glob’ in ruby and os module’s listdir in python we can find all the files and folders that inside sample_folder. Next check it is a file or a folder. If it is a folder we need to iterate through that folder(use recursion ) and get the file paths of files inside the folder. Else it is a file push that file path into our instance array ‘file_array’.

Ruby
Python

def iterate_through_dir(dir_path, file_array)
      file_paths = Dir.glob(dir_path + “/*”)
      file_paths.each do |f|
         if File.file?(f)
            file_array.push(f)
         else
            iterate_through_dir(f, file_array)
         end
      end
end

def iterate_through_dir(dir_path):
      file_paths = os.listdir(dir_path)
      for i in file_paths:
         path_to_dir = dir_path + “/” + i
         if os.path.isdir(path_to_dir) == True:
            iterate_through_dir(path_to_dir)
         else:
            file_array.append(path_to_dir)

Now we got all the file paths of files inside the nested folder sample_folder in @file_array / file_array. Take each element in the @file_array / file_array, and open that file in read mode. Call ‘f.read’ in ruby and ‘f.read()’ in python to get the file contents as a string.

Ruby
Python

      ———
      @file_array.each do |file_path|
      f = File.open(file_path, ‘r’)
      file_contents_in_string = f.read
      ———
      ———

      ———
      for i in file_array:
      f = open(i, ‘r’)
      file_content = f.read()
      ———
      ———

Then call ruby-‘.match’, python – ‘re.search'(import regular expression module first -import re) on file content string to find the string inside the file. If you find the string then put it in an array. If you can’t find then put it in an another array. Before that find the file extensions to get the different type of files and append that file paths to different arrays.

Ruby
Python

———
   if (file_contents_in_string[0..500].match(“your string”))
      files_has_string << file_path
      else
        file_extension = File.basename(file_path).split(‘.’)[1]
        if file_extension == ‘rb’
           rb_files_has_no_string << file_path
        elsif file_extension == ‘erb’
           erb_files_has_no_string << file_path
        else
           unknown_files << file_path
      end
end
end

———
   if re.search(‘find_this_string’, file_content[0:500]):
      files_has_string.append(i)
      else:
       &  file_extension = os.path.basename(i).split(‘.’)[1]
       & if if file_extension == ‘rb’:
           rb_files_no_string.append(i)

        elif file_extension == ‘erb’:
         erb_files_no_string.append(i)
      else:
           unknown_files.append(i)

At last call the print_results method to print results.

Ruby
Python

——–
      print_results(@file_array, rb_files_has_no_string, erb_files_has_no_string, unknown_files)
end

print search_in_file(“/your/path/to/nested/folder”)

——–
      print_results(rb_files_no_string, erb_files_no_string, unknown_files)

print search_in_file(“/your/path/to/nested/folder”)

Output : Ruby

Output : Python

search_a_string
The method ‘print_results’ accepts four arrays and prints the results accordingly.

Advertisements

Turtle graphics programming in python

Using python’s tkinter module we can create a logo style programs. To do this in python import the module tkinter. Draw the class turtle. Initialize the turtle class with coordinates and angle. Write a function draw_turtle. Draw three straight lines to form a triangle. Write another function delete_turtle to delete the lines. To move forward write mv_fwd function with a parameter ‘distance’. In this function first delete the turtle, draw a line to that distance and redraw the turtle. Preserve the angle.

Turtle graphics in python

Visit my github location for source code – http://github.com/abhilashak/logo_in_python

To rotate write rt_lt and rt_rt functions. First delete the existing turtle. From the angle this function calculates the position of new turtle. Redraw it.  rt_rt is just the negative angle of rt_lt.

Programming in python : Classes

Create a class as follows,

>>> class abc():
… a = 1
… b = 2

create x as an instance of the class abc,

>>> x = abc()
>>> x

>>> x.b
2
Create another class with a function definition,

>>> class abc():
… a = 3
… b = 4
… def fun():
… print ‘hello’

>>> x = abc()
>>> x.a
3
>>> x.b
4
>>> x.fun()
Traceback (most recent call last):
File “”, line 1, in
TypeError: fun() takes no arguments (1 given)

We cannot call the function in class abc, as an attribute of x. x has no such an attribute. But the address of x is already given by the interpreter as a parameter to that function. Usually we give an extra parameter ‘self’, have no special meaning.

>>> class abc():
… a = 1
… b = 2
… def fun(self):
… p = 5
… q = 6
… print ‘hello’

>>> x = abc()
>>> x.a
>>> 1
>>> x.p
>>> x.fun()
The above statement causes an error. Because x has no attribute p. ‘x.fun()’ cannot print hello, so little changes are needed to our code and is shown below.

>>> class abc():
… x = 1
… y = 2
… def fun(self):
… self.p = 3
… self.q = 4
… print ‘Hello’

>>> m = abc()
>>> m.p
Traceback (most recent call last):
File “”, line 1, in
AttributeError: abc instance has no attribute ‘p’

Here the interpreter says that the abc instance has no attribute ‘p’.’p’ is an attribute of the function ‘fun’. So create an instance of abc and pass the address of m to ‘self’.

>>> m = abc()
>>> m .fun()
Hello

Programming in Python : Dictionaries

Dictionaries are another data type in python. It can be think as a unordered collection of keys associated with values. The keys can be numbers, strings, or tuples. An empty dictionary is denoted by ‘{ }’. We can view all keys by simply calling keys(). The dict() constructor is using to build a dictionary.

>>> dic = {‘one’:1,’two’:2,’three’:3,’four’:4,’five’:5}

>>> dic
{‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘one’: 1}

>>> dic[‘six’] = 6

>>> dic
{‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4, ‘five’: 5, ‘one’: 1}

>>> del dic[‘five’]

>>> dic
{‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4, ‘one’: 1}

>>> dic[‘seven’] = 7

>>> dic
{‘seven’: 7, ‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4, ‘one’: 1}

>>> dic.key()

Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘dict’ object has no attribute ‘key’

>>> dic.keys()
[‘seven’, ‘six’, ‘three’, ‘two’, ‘four’, ‘one’]

>>> dic[‘seven’]
7
>>> dic[‘one’]
1

>>> ‘one’ in dic
True

>>> ‘three’ in dic
True

>>> ‘kjkk’ in dic
False

>>> del dic[‘one’]

>>> dic
{‘seven’: 7, ‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4}

>>> dic.keys()
[‘seven’, ‘six’, ‘three’, ‘two’, ‘four’]

>>> dic.values()
[7, 6, 3, 2, 4]

>>> a=[(‘aass’,23),(‘iiii’,56),(‘dftj’,38)]

>>> a
[(‘aass’, 23), (‘iiii’, 56), (‘dftj’, 38)]

>>> dict(a)
{‘aass’: 23, ‘iiii’: 56, ‘dftj’: 38}

>>> b = dict(a)

>>> b
{‘aass’: 23, ‘iiii’: 56, ‘dftj’: 38}

>>> dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)
{‘jkhjkhk’: 3434, ‘jhjkhk’: 433, ‘iuijmkm’: 344343}

>>> c = dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)

>>> c
{‘jkhjkhk’: 3434, ‘jhjkhk’: 433, ‘iuijmkm’: 344343}

Programming in Python : Sets

Set is a data type in python. It is an unordered set of elements without duplicates. We can test an element is a member of the set. Set operations can operate on unique letters as given below.

>>> list1 = [‘apple’,’mango’,’pineapple’,’mango’,’apple’,’orange’]

>>> fruit = set(list1)

>>> fruit
set([‘orange’,’mango’,’apple’,’pineapple’])

>>> ‘mango’ in fruit
True

>>> ‘grape’ in fruit
False

>>> a = (‘abhilash’)

>>> a
‘abhilash’

>>> b = (‘abhijith’)

>>> b
‘abhijith’

>>> set(a)
set([‘a’, ‘b’, ‘i’, ‘h’, ‘l’, ‘s’])

>>> set(b)
set([‘a’, ‘b’, ‘i’, ‘h’, ‘j’, ‘t’])

>>> c = set(a)

>>> d = set(b)

>>> c
set([‘a’, ‘b’, ‘i’, ‘h’, ‘l’, ‘s’])

>>> d
set([‘a’, ‘b’, ‘i’, ‘h’, ‘j’, ‘t’])

>>> c-d
set([‘s’, ‘l’])

>>> d-c
set([‘j’, ‘t’])

>>> c |d
set([‘a’, ‘b’, ‘i’, ‘h’, ‘j’, ‘l’, ‘s’, ‘t’])

>>> c & d
set([‘a’, ‘i’, ‘b’, ‘h’])

>>> c ^ d
set([‘s’, ‘t’, ‘j’, ‘l’])

Programming in python: Tuples and sequences

Tuples consists of elements that are enclosed in parenthesis. The empty tuples is represented by ‘()’. The single element tuple is ending with a comma.

>>> t = (‘one’,’two’,’three’)

>>> t
(‘one’,’two’,’three’)

>>> e = ()

>>> e
()

>>> len(e)
0

>>> single = (‘one’,)

>>> single
(‘one’,)

>>> len(single)
1

The statement t = 1223,5676,’one’,’two’ is an example of tuple packing. The elements are packed together in a tuple. The sequence unpacking is also possible. ex: a,b,c,d = t

>>> t = 1223,5676,’one’,’two’

>>> t
(1223,5676,’one’,’two’)

>>> a,b,c,d = t

>>> a
1223

>>> d
‘two’

Programming in Python : Lists

The list data type in python allows more operations compared to the other data types. The items in the lists are enclosed by brackets ‘[]’. It may contain numbers, srtings, tuples or lists (nesting of lists).

>>> list1 = [1,2,3,’how’,’are’,’you’]

>>> list1
[1, 2, 3, ‘how’, ‘are’, ‘you’]

>>> list1[3]
‘how’

>>> list1[3:]
[‘how’, ‘are’, ‘you’]

>>> list1[:2]
[1, 2]

>>> list1[:2] = ‘and’

>>> list1
[‘a’, ‘n’, ‘d’, 3, ‘how’, ‘are’, ‘you’]

>>> list1[:2] = [‘and’]

>>> list1
[‘and’, 3, ‘how’, ‘are’, ‘you’]

>>> list1 = [12,34,56,’s’,’y’]

>>> list1
[12, 34, 56, ‘s’, ‘y’]

>>> list2 = [22,’22’]

We can add members of one list to the members of another list.
>>> list1[3:3] = list2

>>> list1
[12, 34, 56, 22, ’22’, ‘s’, ‘y’]

>>> list3 = [33,list2,’33’]

The following list is nested.
>>> list3
[33, [22, ’22’], ’33’]

>>> list3[1][1]
’22’

>>> list3[1][0]
22

The del statement :

It is used to remove an element from a list when the index of that element is given. It can be used to clear the entire list or remove the variable.