-15
add_numbers( "A1", "Element 560234 65952 6598881 20203256 2165883 659562 654981 24120 261240 31648948 23900 5512400 5512900 5612400 5612900" )

add_numbers( "A2", "Element 261240 31659 5612400 76803256 3165883 659863 654224 44120 261240 31648948 23900 3612200 9512900 5612400 5642924" )

add_numbers( "A3", "Element 841225 65952 2165883 63103256 2165883 644861 344966 84120 161540 31653948 23900 5513426 5518906 5682405 8682932" )

次のような辞書を(上記のtxtファイルから)辞書を取得したい:

{A1: 560234, 65952,6598881, 20203256,2165883, 659562,....}

{A2: 261240 31659 5612400,....}

{A3: 841225 65952 2165883,....}

あなたはなにか考えはありますか?どうすればこれを達成できますか?ありがとうございました。

4

2 に答える 2

6

これを処理したいことを理解する

add_numbers( "A1", "Element 560234 65952 6598881 20203256 2165883 659562 654981 24120 261240 31648948 23900 5512400 5512900 5612400 5612900" )

add_numbers( "A2", "Element 261240 31659 5612400 76803256 3165883 659863 654224 44120 261240 31648948 23900 3612200 9512900 5612400 5642924" )

add_numbers( "A3", "Element 841225 65952 2165883 63103256 2165883 644861 344966 84120 161540 31653948 23900 5513426 5518906 5682405 8682932" )

テキストファイルのリテラルコンテンツを辞書に入れるには、次のようにします。

import re # import regular expression module
d = {}

for line in open("myfile.txt", "r"):
    if not line.strip(): continue        # Skip blank lines
    data = re.findall('"([^"]*)"', line) # Extract text between double quotes

    if len(data) != 2: continue          # There were not exactly two pairs of double quotes, skip this line

    key, value = data
    d[key] = map(int, value.split()[1:]) # Remove "Element" and convert numbers to integers, add to dictionary

正規表現の説明"([^"]*)":

  • "( )"引用符内のものを一致させる
  • [^"]*0 文字以上の任意の文字列"

re.findall結果をリストで返します。

編集

エラーが発生します。ValueError: アンパックするには複数の値が必要です

ファイルには二重引用符が 2 つ含まれていない行が必要です。仕様に一致しない行を無視するように上記のコードを更新しました。

于 2013-05-17T08:30:59.710 に答える
5
import re,ast
def add_numbers(d,key,elements): #we pass in a reference to a dict, which we update
    d[key] = map(int,elements.split()[1:]) #Returns ["Element",...], so we select all but first [1:]
dic = {}
with open('file.txt') as f:
    for line in f:
        key,elems = ast.literal_eval(re.search(r'\((.+)\)',line).group(0))
        add_numbers(dic,key,elems)

プロデュース

>>> 
{'A1': [560234, 65952, 6598881, 20203256, 2165883, 659562, 654981, 24120, 261240, 31648948, 23900, 5512400, 5512900, 5612400, 5612900], 'A3': [841225, 65952, 2165883, 63103256, 2165883, 644861, 344966, 84120, 161540, 31653948, 23900, 5513426, 5518906, 5682405, 8682932], 'A2': [261240, 31659, 5612400, 76803256, 3165883, 659863, 654224, 44120, 261240, 31648948, 23900, 3612200, 9512900, 5612400, 5642924]}
于 2013-05-17T08:27:09.510 に答える