Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python在文件中查找特殊单词?_Python_Regex_Python 2.7_Python 3.x - Fatal编程技术网

如何使用Python在文件中查找特殊单词?

如何使用Python在文件中查找特殊单词?,python,regex,python-2.7,python-3.x,Python,Regex,Python 2.7,Python 3.x,我在一个目录中有一堆.java文件,我想通过python代码将它们编译成.class文件 正如您所知,Javac命令行工具是我必须使用的工具,它要求.java文件的名称与类名相等。不幸的是,对于我的.java文件来说,它不是。我的意思是,他们有不同的随机名称,与他们的类名不相等 因此,我需要从.java文件的内容中提取类的名称。如果指定了类定义的行,这很简单,但实际上不是。.java文件顶部可能包含一些注释,这些注释也可能包含类或包单词 问题是如何提取每个文件的包和类名 例如,这是其中一个的内容

我在一个目录中有一堆
.java
文件,我想通过python代码将它们编译成
.class
文件

正如您所知,
Javac
命令行工具是我必须使用的工具,它要求
.java
文件的名称与类名相等。不幸的是,对于我的
.java
文件来说,它不是。我的意思是,他们有不同的随机名称,与他们的类名不相等

因此,我需要从
.java
文件的内容中提取类的名称。如果指定了类定义的行,这很简单,但实际上不是。
.java
文件顶部可能包含一些注释,这些注释也可能包含类或包单词

问题是如何提取每个文件的包和类名

例如,这是其中一个的内容:

//这是一个类名为HelloWorldApplet的示例包。在这个包里,我们胡说八道,这个类胡说八道。
包helloWorldPackage;
//这是另一条评论,里面可能有也可能没有“包”和“类”两个词。
导入javacard.framework.APDU;
导入javacard.framework.Applet;
导入javacard.framework.ISO7816;
导入javacard.framework.ISOException;
导入javacard.framework.Util;
/*这也是一个多行注释。诸如此类的包装,诸如此类的包装*/
公共类HelloWorldApplet扩展小程序
{
私有静态最终字节[]helloWorld={(字节)'H',(字节)'e',(字节)'l',(字节)'l',(字节)'o',(字节)'W',(字节)'o',(字节)'r',(字节)'l',(字节)'d',};
私有静态最终字节HW_CLA=(字节)0x80;
私有静态最终字节HW_INS=(字节)0x00;
公共静态无效安装(字节[]bArray,短bOffset,字节bLength)
{
新的HelloWorldApplet()。寄存器(bArray,(short)(bOffset+1),bArray[bOffset]);
}
公共作废流程(APDU APDU)
{
如果(选择Applet())
{
返回;
}
byte[]buffer=apdu.getBuffer();
字节CLA=(字节)(缓冲区[ISO7816.OFFSET_CLA]&0xFF);
字节INS=(字节)(缓冲区[ISO7816.OFFSET_INS]&0xFF);
如果(CLA!=HW_CLA)
{
ISOException.throwIt(不支持ISO7816.SW_CLA_);
}
开关(INS)
{
案例硬件插件:
getHelloWorld(apdu);
打破
违约:
ISOException.throwIt(ISO7816.SW不支持);
}
}
私有void getHelloWorld(APDU APDU)
{
byte[]buffer=apdu.getBuffer();
短长度=(短)helloWorld.length;
Util.arrayCopyNonAtomic(helloWorld,(short)0,buffer,(short)0,(short)length);
apdu.setOutgoingAndSend((短)0,长度);
}
}
如何提取每个文件的包名(即
helloWorldPackage
)和类名(即
HelloWorldApplet

请注意,
.java
文件中可能有不同的类,但我需要仅扩展
Applet
的类的名称

更新:

我尝试了以下方法,但没有成功(Python 2.7.10):


这个正则表达式适合我<代码>(?在许多情况下,一个简单的正则表达式可以工作

如果您想100%确定,我建议使用一个成熟的Java解析器来解析每个文件,然后遍历AST以提取类名

差不多

import glob
import javalang

# look at all .java files in the working directory
for fname in glob.glob("*.java"):
    # load the sourcecode
    with open(fname) as inf:
        sourcecode = inf.read()

    try:
        # parse it to an Abstract Syntax Tree
        tree = javalang.parse.parse(sourcecode)
        # get package name
        pkg = tree.package.name

        # look at all class declarations
        for path, node in tree.filter(javalang.tree.ClassDeclaration):
            # if class extends Applet
            if node.extends.name == 'Applet':
                # print the class name
                print("{}: package {}, main class is {}".format(fname, pkg, node.name))

    except javalang.parser.JavaSyntaxError as je:
        # report any files which don't parse properly
        print("Error parsing {}: {}".format(fname, je))

sample.java: package helloWorldPackage, main class is HelloWorldApplet

您可以使用以下正则表达式:

import re
string = your_string_here
classes = [x.strip() for x in re.findall(r'^(?:public class|package) ([^;]+?)(?=extends|;)', string, re.MULTILINE)]
# look for public class or package at the start of the line 
# then anything but a semicolon
# make sure the match is immediately followed by extends or a colon
print classes
# ['helloWorldPackage', 'HelloWorldApplet']

简单到?这就是你需要的文件吗?试着打印它。
import glob
import javalang

# look at all .java files in the working directory
for fname in glob.glob("*.java"):
    # load the sourcecode
    with open(fname) as inf:
        sourcecode = inf.read()

    try:
        # parse it to an Abstract Syntax Tree
        tree = javalang.parse.parse(sourcecode)
        # get package name
        pkg = tree.package.name

        # look at all class declarations
        for path, node in tree.filter(javalang.tree.ClassDeclaration):
            # if class extends Applet
            if node.extends.name == 'Applet':
                # print the class name
                print("{}: package {}, main class is {}".format(fname, pkg, node.name))

    except javalang.parser.JavaSyntaxError as je:
        # report any files which don't parse properly
        print("Error parsing {}: {}".format(fname, je))
sample.java: package helloWorldPackage, main class is HelloWorldApplet
import re
string = your_string_here
classes = [x.strip() for x in re.findall(r'^(?:public class|package) ([^;]+?)(?=extends|;)', string, re.MULTILINE)]
# look for public class or package at the start of the line 
# then anything but a semicolon
# make sure the match is immediately followed by extends or a colon
print classes
# ['helloWorldPackage', 'HelloWorldApplet']