简体   繁体   中英

Recursion Java vs Python

last week i made this java file wondering to search in my pc files which contains certain words i input. After to have done it i thought "why not translating it in python?" and in python i have seen that it runs out of memory (because of the recursion), but in java didn't (in python the code works if i dont give a lot of dirs and files), i put here the 2 codes and the error (java vs python) so u can help me(sorry for my english i am not mother tongue).

JAVA:

package com.company;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    System.out.println("Input path to start(remember the / at the end):");
    Scanner input = new Scanner(System.in);
    String path=input.nextLine();
    ArrayList<String> words= new ArrayList<>();
    String word="";
    while(!word.equals("//quit")){
        System.out.println("Input word to search (input://quit to stop):");
        word=input.nextLine();
        if(!word.equals("//quit"))
            words.add(word);
    }
    Finder finder= new Finder(path,castToArray(words));
    finder.readFile();
}

private static void readFiles(Finder finder){
    String[] files = finder.printFiles();
    for(int i=0; i< files.length;i++){
        System.out.println(files[i]);
    }
}

private static String[] castToArray(ArrayList<String> words){
    String[] w0rds = new String[words.size()];
    for(int i=0; i< words.size(); i++){
        w0rds[i]= words.get(i);
    }
    return w0rds;
}

}

class Finder {

private String[] words;
private File file;
private String path;

Finder(String path,String... words){
    this.words=words;
    this.path=path;
    file= new File(path);
}

public String[] printFiles(){
    String[] files;
    files=file.list();
    return files;
}

public void readFile(){
    String[] files= printFiles();
    for(int i=0; i< files.length;i++){
        File f = new File(file.getPath()+"/"+files[i]);
        if(!f.isDirectory()){
            searchWord(f,words);
        }else {
            Finder finder = new Finder(path+f.getName()+"/",words);
            finder.readFile();
        }
    }
}

public File getFile() {
    return file;
}

public void searchWord(File file,String... words){
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new FileInputStream(file));
        byte[] bytes = new byte[512];
        dis.readFully(bytes);
        String obj = new String(bytes);
        for(int i=0; i< words.length;i++){
            if(obj.contains(words[i])){
                System.out.println(file.getName());
                break;
            }
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }

}

}

PYTHON:

import os

class Finder:
    path = ""
    words= []

    def readFile(self,path,words):
        new_file = open(path, "r")
        data=new_file.read(8192)
        new_file.close()
        for word in words:
        if(data.find(word,0,len(data))!=-1):
            print "name: "+new_file.name+" path: "+path
            break

def __init__(self,path, words):
    self.path=path
    self.words=words      

def __del__(self):
    files=os.listdir(path)
    for file in files:
        if(os.path.isdir(path+file)!=True):
            self.readFile(path+file,words)
        else:
            dirpath = path+file+"/"
            finder = Finder(path,words)                            

path= raw_input("input path to start(remember the / at the end):\n")
words=[]
word = ""
while word != "//quit":
    word=raw_input("input word to search (write //quit to start     searching):\n")
    if word != "//quit":
        words.append(word);
print "start searching for "+str(words)+"..."
finder = Finder(path,words)

PYTHON ERROR:

Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4d40>> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4c68>> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4d40>> ignored
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method Finder.__del__ of <__main__.Finder instance at 0x7f5c0b4f4c68>> ignored

In python, you rarely should use the __del__ method. It is a special magic method that is called at an arbitrary time (when the object is garbage-collected) with very few applications and multiple caveats. Instead, for most use cases, you should use a .close() method you call explicitly or with a context manager like contextlib.closing .

That said, I don't know why you made a __del__ method at all since in your java code there is nothing like that. Closest java thing would be a finalize method, but you're not using it, so why did you chose to use __del__ in your translation?

Anyway, in python you can use os.walk() instead of os.listdir() to traverse your directory tree - os.walk() is iteratively recursive so it can handle any path depth without running out of call stack space:

for pth, dirs, files in os.walk(path):
    for filename in files:
        self.readFile(os.path.join(pth, filename))

This code snippet will call readFile with all files in all subfolders.

The problem in your python code is, that you use the global path variable in __del__ instead of self.path . Therefore you get an infinite recursion.

Better convert your class into functions:

import os

def readFile(path, words):
    with open(path, "r") as new_file:
        data = new_file.read(8192)
    for word in words:
        if word in data:
            print "name: {} path: {}".format(new_file.name, path)
            break

def search(path, words):
    files = os.listdir(path)
    for filename in files:
        fullname = os.path.join(path, filename)
        if not os.path.isdir(fullname):
            readFile(fullname, words)
        else:
            search(fullname, words)

path = raw_input("input path to start: ")
words = []
while True:
    word = raw_input("input word to search (write //quit to start searching): ")
    if word == "//quit":
        break
    words.append(word)
print "start searching for {}...".format(', '.join(words))
search(path, words)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM