I want Python to search for multiple java files in the target directory and get the defined class name

Asked 1 weeks ago, Updated 1 weeks ago, 168 views

I would like to explore several java files in the target directory and earn the defined class name.For example, if you have target_dir/Car.java Train.java, I would like to receive the class names Car and Train.Also, instead of simply returning the file name as a class name, I would like to take the form of searching the file one by one.I've created it, but I can only read one java file and I can't think of a solution.I would appreciate it if you could let me know if there are any corrections and better implementation methods.

importos
for root, dirs, files in os.walk(top='./target_dir'):
  for file in files:
    if not file.lower().endswith('.java')):
       continue

    filePath=os.path.join(root,file)

    # read line by line
    with open(filePath) asf:
        lines=f.readlines()

    # omit line breaks
    lines = [ line.rstrip('\n') .split() for line in lines ]
    print(lines)
    
    # Display the code that follows the class description
    for i in range (len(lines)) :
        if "class" in lines [i]:
            classline=lines[i]
    print(classline)
    print(classline [classline.index("class")+1])

Error Screen

python java

2022-11-24 08:39

1 Answers

This example shows how to enumerate class names using a regular expression.

sample code

import glob
import re

dir_path=r"./target_dir" 
pattern=re.compile(r"\s?class\s+(\w+)")

for path in glob.glob(rf "{dir_path}/*.java"):
    with open(path, "r", encoding="sjis") asf:
        s=f.read()
        for min re.finder (pattern, s):
            class_name = m.group(1)
            The print(f'{class_name} class was found in "{f.name}".')
  • You can extract multiple classes in the file.
  • Do not recurs the folder
  • Do not discriminate between comment lines
  • Process the encoding of the file with the shift JIS.


2022-11-24 09:34

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.