2017-04-25 8 views
0

私はこれを始めたが、エラー処理とパターンマッチングロジックをめちゃくちゃにされ input file linkファイル内のパターン一致するテキストはありますか?

を次のように見て、この output file link

のような出力ファイルを作成する必要があり、入力ファイルを持っています(特に、URL内とデータ内での出現)。また、出力ファイルの平均値は、ゼロ以外の値またはゼロ以外の値の平均値です。

with open("input.txt") as f: 
next(f) # skips header 
for line in f: 

    cleanline = re.sub('::',':',line) # handles the two :: case 
    newline = re.split("[\t:]",cleanline) #splits on either tab or : 
    print newline 
    x=0 
    total=0 
    for i in range(3,7): 
    if newline[i] <> 0 or newline[i] != None: 
     x+=1 
     total+=total 
     avg=total/x 
     print avg 
+0

私は 'csv'モジュールを使ってファイルを読み書きすることをお勧めします。それはあなたのための特別なケースの多くを処理することができます。また、あなたの質問を編集して、入力ファイルの長い例とそれに含まれるすべての特殊な例を表示し、期待される出力がどのように表示されるかを示してください。 – martineau

+0

私は入力ファイルと出力ファイルの画像を追加して、何を改善しようとしているのかを説明しました。それを提案してくれてありがとう。投稿はあまりにも混乱していた – ashu138

+0

実際に私は両方のファイルから行をカットし、あなたの質問(4つのスペースでインデントされている)に貼り付けることを意味した。そうすれば、誰かが最初にコードを実行できるようになり、2番目のコードで結果を確認することができます。 – martineau

答えて

0

これは別の角度からアプローチすることをお勧めします。まず、各行をタブに沿って分割し、各エントリを個別に検証します。これにより、各エントリの正規表現をコンパイルし、より正確なエラーメッセージをコンパイルすることができます。私はあなたがエントリーで見ることを期待正確に把握していないとして、私は、エントリを検証するためにreの呼び出しを追加しませんでした

from __future__ import print_function 

with open("input.txt") as in_file, open("output.txt", 'w') as out_file: 
    next(in_file) # skips header 

    for line in in_file: 
     error_message = [] 
     # remove line break character and split along the tabs 
     id_and_date, user_id, p1, p2, p3, p4, url = line.strip("\n").split("\t") 

     # split the first entry at the first : 
     split_id_date = id_and_date.split(":", 1) 
     if len(split_id_date) == 2: 
      order_id, date = split_id_date 
     elif len(split_id_date) == 1: 
      # assume this is the order id 
      # or do something 
      order_id, date = (split_id_date[0], "") 
      error_message.append("Invalid Date") 
     else: 
      # set default values if nothing is present 
      order_id, date = ("", "") 
     # validate order_id and date here using re.match 
     # add errors to error_message list: 
     # error_message.append("Invalid Date") 

     # calculate average price 
     # first, compile a list of the non-zero prices 
     nonzero_prices = [int(x) for x in (p1, p2, p3, p4) if int(x) > 0] # this can be done more efficient 
     # compute the average price 
     avg_price = sum(nonzero_prices)/len(nonzero_prices) 

     # validate url using re here 
     # handle errors as above 

     print("\t".join([order_id, date, user_id, str(avg_price), url, ", ".join(error_message)]), file=out_file) 

:これを行うには良い方法は、タプルをアンパックし、分割された方法です。しかし、私はre.matchまたは類似のものへの呼び出しが妥当であるとのコメントを追加しました。

こちらがお役に立てば幸いです。

関連する問題