python - 如何删除文件中两个重复 block 之一?

标签 python regex file-io duplicates

我有一个难题。我知道有很多 Python 大师。所以请帮助我。我有一个巨大的日志文件。格式是这样的:

[text hello world yadda

          lines lines lines

          exceptions]

[something i'm not interested in]

[text hello world yadda

          lines lines lines

          exceptions]

等等... 所以 block 1 和 block 3 是相同的。而且这样的案例还有很多。我的问题是如何读取该文件并仅在输出文件中写入唯一的 block ?如果有重复,应该只写一次。有时两个重复 block 之间存在多个 block 。我实际上正在进行模式匹配,这是目前的代码。它只匹配模式,但不会对重复项执行任何操作。

import re
import sys
from itertools import islice
try:
   if len(sys.argv) != 3:
      sys.exit("You should enter 3 parameters.")
   elif sys.argv[1] == sys.argv[2]:
      sys.exit("The two file names cannot be the same.")
   else:
       file = open(sys.argv[1], "r")
       file1 = open(sys.argv[2],"w")
       java_regex = re.compile(r'[java|javax|org|com]+?[\.|:]+?', re.I)  # java 
       at_regex = re.compile(r'at\s', re.I)    # at

       copy = False  # flag that control to copy or to not copy to output

       for line in file:
          if re.search(java_regex, line) and not (re.search(r'at\s', line, re.I) or re.search(r'mdcloginid:|webcontainer|c\.h\.i\.h\.p\.u\.e|threadPoolTaskExecutor|caused\sby', line, re.I)):
              # start copying if "java" is in the input
              copy = True
          else:
              if copy and not re.search(at_regex, line):
                  # stop copying if "at" is not in the input
                  copy = False

          if copy:
              file1.write(line)



       file.close()
       file1.close()

except IOError:
       sys.exit("IO error or wrong file name.")
except IndexError:
       sys.exit('\nYou must enter 3 parameters.') #prevents less than 3 inputs which is mandatory
except SystemExit as e:                       #Exception handles sys.exit()
       sys.exit(e)

我不在乎这是否必须在这段代码中(删除重复项)。它也可以位于单独的 .py 文件中。没关系 这是日志文件的原始片段:

javax.xml.ws.soap.SOAPFaultException: Uncaught BPEL fault http://schemas.xmlsoap.org/soap/envelope/:Server     
    at org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.createSystemException(MethodMarshallerUtils.java:1326) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.demarshalFaultResponse(MethodMarshallerUtils.java:1052) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.marshaller.impl.alt.DocLitBareMethodMarshaller.demarshalFaultResponse(DocLitBareMethodMarshaller.java:415) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.getFaultResponse(JAXWSProxyHandler.java:597) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.createResponse(JAXWSProxyHandler.java:537) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invokeSEIMethod(JAXWSProxyHandler.java:403) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invoke(JAXWSProxyHandler.java:188) ~[org.apache.axis2.jar:na]
com.hcentive.utils.exception.HCRuntimeException: Unable to Find User Profile:null
    at com.hcentive.agent.service.AgentServiceImpl.getAgentByUserProfile(AgentServiceImpl.java:275) ~[agent-service-core-4.0.0.jar:na]
    at com.hcentive.agent.service.AgentServiceImpl$$FastClassByCGLIB$$e3caddab.invoke(<generated>) ~[cglib-2.2.jar:na]
    at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) ~[cglib-2.2.jar:na]
    at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689) ~[spring-aop-3.1.2.RELEASE.jar:3.1.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) ~[spring-aop-3.1.2.RELEASE.jar:3.1.2.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) ~[spring-tx-3.1.2.RELEASE.jar:3.1.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) ~[spring-aop-3.1.2.RELEASE.jar:3.1.2.RELEASE]
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64) ~[spring-security-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
javax.xml.ws.soap.SOAPFaultException: Uncaught BPEL fault http://schemas.xmlsoap.org/soap/envelope/:Server      
    at org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.createSystemException(MethodMarshallerUtils.java:1326) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.demarshalFaultResponse(MethodMarshallerUtils.java:1052) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.marshaller.impl.alt.DocLitBareMethodMarshaller.demarshalFaultResponse(DocLitBareMethodMarshaller.java:415) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.getFaultResponse(JAXWSProxyHandler.java:597) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.createResponse(JAXWSProxyHandler.java:537) ~[org.apache.axis2.jar:na]
    at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invokeSEIMethod(JAXWSProxyHandler.java:403) ~[org.apache.axis2.jar:na]  



And so on and on....

最佳答案

您可以使用以下方法删除重复的 block :

import re
yourstr = r'''
[text hello world yadda

      lines lines lines

      exceptions]

[something i'm not interested in]

[text hello world yadda

      lines lines lines

      exceptions]
'''
pat = re.compile(r'\[([^]]+])(?=.*\[\1)', re.DOTALL)
result = pat.sub('', yourstr)

请注意,仅保留最后一个 block ,如果您想要第一个 block ,则必须反转字符串并使用此模式:

 (][^[]+)\[(?=.*\1\[)

然后再次反转字符串。

关于python - 如何删除文件中两个重复 block 之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21488186/

相关文章:

python - 如何让 python 信任我服务器的 TLS 自签名证书 : ssl. SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败

python - 从功能上打乱列表

c# - 如何通过正则表达式检查和提取字符串?

python - Python 正则表达式前瞻中的匹配组

php - 在 PHP 中处理文件和 utf8

c - 将文件读入结构体

c++ - 如何使用 NASM 程序集读取和修改文件的字节,并使用 C++ 打开/关闭文件?

python - 尝试使用 Pandas 数据框删除包含 nan 或 inf 的行时出现问题

python - pip install datefinder 出错

php - 忽略正在搜索的标点符号