次の名前のファイルに次のテキストがありますmy_text.txt
:
David: 2
Barbara: 97.2
David: negative
William:
Lynn: 725
Nancy : 87
David: 54
Lewis: 18.30
Sue: 3193.74
James: 41.73
David: 974.1
空白行と数値以外の値に注意してください。ファイルからデータをインポートして辞書を作成するためのコードは次のとおりです。
import collections
def make_dictionary(file_name):
d = collections.defaultdict(float)
with open(file_name, 'r') as file:
for line in file:
line = line.strip()
# skip blank lines
if line == '':
continue
# split on the colons
elif ':' in line:
key, val = line.split(':')
d[key.strip()] += val.strip()
return d
make_dictionary('my_text.txt')
辞書の値をインクリメントできるようにしたいと思います。たとえば、Davidのキーと値のペアは次のようになります。
David : 1030.1
(ファイル内の3つの値の合計)
次のエラーが発生します:
TypeError: unsupported operand type(s) for +=: 'float' and 'str'
これを解決する方法を知っている人はいますか?
ありがとう!
プログラムが文字列に整数を追加しようとしているという事実によって引き起こされたエラー、
つまり、David:negativeなので、処理する以外はtryを使用できます。
r = []
with open('t.txt', 'r') as file:
for line in file:
line = line.strip()
# skip blank lines
if line == '':
continue
# split on the colons
elif ':' in line:
key, val = line.split(':')
# try converting it into float else set it set as 0.
try:
val = float(val.strip())
except:
val = 0
r.append({'name': key.strip(), 'val': val})
次に、次のように要約できます。
d = collections.defaultdict(float)
for item in r:
d[item['name']] += item['val']
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加