簡體   English   中英

遞歸Java與Python

[英]Recursion Java vs Python

上周,我做了這個Java文件,想在我的PC文件中進行搜索,其中包含我輸入的某些單詞。 完成之后,我想“為什么不在python中翻譯它?” 在python中,我已經看到它用完了內存(由於遞歸),但是在java中卻沒有(在python中,如果我沒有給出很多dirs和文件,代碼就可以工作),我在這里放了2個代碼,錯誤(java vs python),所以你可以幫助我(對不起我的英語,我不是母語)。

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) {
    }

}

}

蟒蛇:

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錯誤:

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

在python中,您很少應該使用__del__方法。 這是一種特殊的魔術方法,在很少的應用程序和多個警告的情況下,可以在任意時間(當對象被垃圾回收時)調用。 相反,在大多數情況下,應使用顯式調用的.close()方法,或與contextlib.closingcontextlib.closing管理器一起使用。

就是說,我根本不知道為什么要創建__del__方法,因為在Java代碼中沒有這樣的東西。 最接近的Java東西將是finalize方法,但是您沒有使用它,那么為什么選擇在翻譯中使用__del__

無論如何,在python中,您可以使用os.walk()而不是os.listdir()遍歷目錄樹os.walk()是迭代遞歸的,因此它可以處理任何路徑深度而不會耗盡調用堆棧空間:

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

此代碼段將調用readFile及其所有子文件夾中的所有文件。

在你的Python代碼的問題是,你使用全局path變量__del__而不是self.path 因此,您將獲得無限遞歸。

更好地將您的類轉換為函數:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM