[英]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.closing
等contextlib.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.