2016-10-02 4 views
0

にそれらを書く:私は興味がどのようなPythonの - 私は以下のようなログファイル持っているログファイルから文字列を抽出し、別のファイル

sw2 switch_has sw2_p3. 
sw1 transmits sw2_p2 
/* BUG: axiom too complex: SubClassOf(ObjectOneOf([NamedIndividual(#t_air_sens2)]),DataHasValue(DataProperty(#qos_type),^^(latency,http://www.xcx.org/1900/02/22-rdf-syntax-ns#PlainLiteral))) */ 
/* BUG: axiom too complex: SubClassOf(ObjectOneOf([NamedIndividual(#t_air_sens2)]),DataHasValue(DataProperty(#topic_type),^^(periodic,http://www.xcx.org/1901/11/22-rdf-syntax-ns#PlainLiteral))) */ 
... 

を、/* BUG...ラインから特定の単語を抽出することで、 、別のファイルに以下のようなものをそれらを書く:

t_air_sens2 qos_type latency 
t_air_sens2 topic_type periodic 
... 

私は以下のようなシェルでawkと正規表現の助けを借りてこれを行うことができます。

awk -F'#|\\^\\^\\(' '{for (i=2; i<NF; i++) printf "%s%s", gensub(/[^[:alnum:]_].*/,"",1,$i), (i<(NF-1) ? OFS : ORS) }' output.txt > ./LogErrors/Properties.txt 

Pythonを使用してそれらを抽出するにはどうすればよいですか? (私は再び正規表現を使用するか?)

答えて

1

もちろん正規表現を使うことができます。私は行ごとに読んで、最初に'/* BUG:'という行をつかんで、必要に応じてそれらを解析します。

import re 

target = r'/* BUG:' 
bugs = [] 
with open('logfile.txt', 'r') as infile, open('output.txt', 'w') as outfile: 
    # loop through logfile 
    for line in infile: 
     if line.startswith(target): 
      # add line to bug list and strip newlines 
      bugs.append(line.strip()) 
      # or just do regex parsing here 
      # create match pattern groups with parentheses, escape literal parentheses with '\' 
      match = re.search(r'NamedIndividual\(([\w#]+)\)]\),DataHasValue\(DataProperty\(([\w#]+)\),\^\^\(([\w#]+),', line) 
      # if matches are found 
      if match: 
       # loop through match groups, write to output 
       for group in match.groups(): 
        outfile.write('{} '.format(group)) 
       outfile.write('\n') 

Pythonは、かなり強力な正規表現モジュールが内蔵されていますre module

することができますsearch for a given pattern, then print out the matched groups as needed

注:raw stringsr'xxxx')を使用すると、エスケープされていない文字を使用できます。

関連する問題