2017-12-01 10 views
0

私は、作業するテキストファイルに次のデータを持っています。Python辞書に更新値を追加する

10月26日1時12分午後
»corwinte:Rhad /設定料金にAshar配達(64):31895 CR 10月26日1時12分午後
»corwinte:生息地-01にAshar配達(32) /設定料金:15716 CR 10月24日4時37分午後
»ダゴンのハマースミス:LUS /設定料金にAshar配達(23):11871 CR 10月24日4時33分午後
»ドラゴン:Ashar配達(74)Enalaへ/セット料金:38192 CR Oct 24th 04:33 pm
»ダゴンハンマー:Ashar Delivery(54)to Enala/Set料金:27870 CR Oct 24th 04:33 pm
»ドラゴン:CEAS /設定料金にAshar配達(38):Turroth /設定料金にAshar配達(45):23225 CR 10月24日4時33分午後
»Falconner 19612 CR

私はちょうどのpythonを学んでいますだからここに私の大雑把なコードがあります、それは私がやりたいと思うすべてをしませんが、それはいくつかのことを行い、そしてあるものは適切ではありません。

まず、日付で始まる行には興味がないので、無視します。 私が望むのは、コードがテキストファイルを通過するために、すべての名前をクレジット(CR)値と共に収集し、それぞれのパーセントを計算し、その名前で合計を保存することです。

これまでのところ、私はパーセンテージを尋ね、名前を集めて、すべてのエントリーのパーセンテージを得ることができました。

ここに私のコードです。

inp = input('enter the name of the file to be opened\n') #asks for a file,opens it,a guard to handle misspelled or files that don't exist 
try: 
    fhand = open(inp) 
except: 
    print('Are you on medications? there is no',inp) 
    exit() 
per = input('Enter the percentage you would like to calculate from,percentage of the fees recieved') 
perc = float(per) 
for line in fhand: 
    if not line.startswith('»'): continue 
    words = line.rstrip().split() #stripping the right spaces and splitting into words 
    feesrecieved = words[-2] 
    actam = float(feesrecieved)*perc/100 
    print(words[1], actam) 

どのようにすれば、各名前の合計計算値を教えてもらえますか? I.Eすべてのドラゴンズは、すべてのダーグーンhaulsなどhauls、hauls。 ありがとうございました!

答えて

1

私はあなたの質問を理解すると思います。 私はそれをdictに追加し、私が行っているように値を更新します。あなたはパーセンテージを見つけた後か前に追加して、最後

で合計をcaculateするか

per = input('Enter the percentage you would like to calculate 
from,percentage of the fees recieved') 
perc = float(per) 
totalFees = {} // create empty dict 
for line in fhand: 
    if not line.startswith('»'): continue 
    words = line.rstrip().split() #stripping the right spaces and splitting into words 
    feesrecieved = words[-2] 
    actam = float(feesrecieved)*perc/100 
    print(words[1], actam) 
    totalFees[words[1]] = totalFees.get([words[1], 0) + actam //updating dict 

関連する問題