如何从python文本文件中删除某些行?



我试图从文本文件中删除特定行,这基本上是txt格式的java代码。我试图从文本中删除多评论,这意味着脚本应该读取文件并删除以"/"开头的多评论。并以/和"\"结尾、"package"one_answers"import"。

我正在使用这个代码,它上次为我工作,但现在它不工作

代码
import re
import sys
import codecs
txt = "H:APK_Source_Code_Mergedsstest1.txt"
with open(txt, 'r',encoding= 'utf-8', errors= 'ignore') as fil:
    file = fil.read()
wtalc = re.sub(r"//.*?", '', file, flags=re.S)
wtslc = re.sub(r"/*.*?*/", '', wtalc, flags=re.S)
wtblc = re.sub(r"import.*?", '', wtslc, flags=re.S)
wtblc = re.sub(r"package.*?", '', wtslc, flags=re.S)
print(wtblc)

基本上,它是一个txt文件。上面的代码完美地工作很好,如果我从文本字符串中读取并删除某些行,那么它工作得很好。但是如果我从文件中读取并删除,它根本不会删除任何行。

package net.youmi.android.b.a.e.c.g;
import net.youmi.android.b.a.e.a.b.g;
import net.youmi.android.b.a.e.a.b.i;
import net.youmi.android.b.a.e.a.b.l;
import org.json.JSONObject;
//asdasbdaiygd
/* loaded from: classes.dex */
public final class a extends l {
    /* JADX WARN: Failed to parse debug info
    java.lang.IllegalArgumentException: newPosition > limit: (67103403 > 2726956)
        at java.base/java.nio.Buffer.createPositionException(Buffer.java:318)
        at java.base/java.nio.Buffer.position(Buffer.java:293)
        at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:1158)
        at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:263)
        at jadx.plugins.input.dex.sections.SectionReader.absPos(SectionReader.java:82)
        at jadx.plugins.input.dex.sections.debuginfo.DebugInfoParser.process(DebugInfoParser.java:84)
        at jadx.plugins.input.dex.sections.DexCodeReader.getDebugInfo(DexCodeReader.java:118)
        at jadx.core.dex.nodes.MethodNode.getDebugInfo(MethodNode.java:546)
        at jadx.core.dex.visitors.debuginfo.DebugInfoAttachVisitor.visit(DebugInfoAttachVisitor.java:39)
     */
    //Override // net.youmi.android.b.a.e.a.b.l
    protected JSONObject a(i iVar, g gVar) {
        return null;
    }
} 

如果我从文本字符串(从变量)中读取和删除某些行,上面的脚本工作得非常好。但是如果我从文件中读取并删除它,它根本不会删除任何行。

您有错误的正则表达式,以便期望".""*"作为字符串,您需要在其之前放置:

import re
import sys
import codecs
txt = "hi.txt"
with open(txt, 'r',encoding= 'utf-8', errors= 'ignore') as fil:
    file = fil.read()
wtalc = re.sub(r"//.*?n", '', file)
wtslc = re.sub(r"/*.*?*/", '', wtalc, flags=re.S)
x = re.sub(r"import.*?n", '', wtslc)
x = re.sub(r"package.*?n", '', x)
print(x)

这应该是诀窍。

您刚刚以读取模式打开文件,并将更改的数据赋值给变量。你还没有修改文件。现在将数据写入file:

https://docs.python.org/3/tutorial/inputoutput.html读和写文件

最新更新