3

次のインデックスをファイルに書き込む方法を知りたいです。以下のインデックスは、私が作成した関数から返されます。

myIndex = {'incorporating': {2047: 1}, 'understand': {2396: 1}, 'format-free': {720: 1}, 'function,': {1579: 1, 485: 1, 831: 1}, '411)': {2173: 1}, 'augmented': {1350: 1}}

このようなものが出力ファイルに表示されるようにします。

'incorporating': {2047: 1} 
'understand': {2396: 1}
'format-free': {720: 1}
'function,': {1579: 1, 485: 1, 831: 1}, '411)': {2173: 1}
'augmented': {1350: 1}

これは私が行ったコードです。writeLine を使用しようとしましたが、ファイルの出力が台無しになりました。そこで、ピクルスのような他の方法を探しました。

def ToFile(self):
indList = myIndex.constructIndex()  # a function to get the index above
filename = "myfile.txt"
outfile = open(filename, 'wb')
pickle.dump(indexList, outfile)

outfile.close()

ファイルを確認しましたが、得たものは次のとおりです。

ssS'incorporating'
p8317
(dp8318
I2047
I1
ssS'understand'
p8319
(dp8320
I2396
I1
ssS'format-free'
p8321
(dp8322
I720
I1
ssS'function,'
p8323
(dp8324
I1579
I1
sI485
I1
sI831
I1
ssS'411)'
p8325 
(dp8326
I2173
I1
ssS'augmented'
p8327
(dp8328
I1350
I1
ss.
4

2 に答える 2

2

ファイルへの書き込みだけを直接試す必要があります。

for key in myIndex:
    outfile.write("'" + key + "': " + str(myIndex[key]) + "\n")
于 2013-11-12T20:36:36.670 に答える
2

Pickle は良いものではありませんが、データをファイルにシリアライズして、後で効率的にデシリアライズできるようにすることを目的としています。PrettyPrintモジュールなどの他のモジュールは、Python データを適切な方法で出力することを目的としています。ただし、後でデータを逆シリアル化できるようにすることが目標である場合は、JSON形式とそのPython モジュールを確認できます。

>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(myIndex)
{   '411)': {2173: 1},
    'augmented': {1350: 1},
    'format-free': {720: 1},
    'function,': {485: 1, 831: 1, 1579: 1},
    'incorporating': {2047: 1},
    'understand': {2396: 1}}
>>> import json
>>> output = json.dumps(myIndex,sort_keys=True,indent=4, separators=(',', ': '))
>>> print(output)
{
    "411)": {
        "2173": 1
    },
    "augmented": {
        "1350": 1
    },
    "format-free": {
        "720": 1
    },
    "function,": {
        "485": 1,
        "831": 1,
        "1579": 1
    },
    "incorporating": {
        "2047": 1
    },
    "understand": {
        "2396": 1
    }
}
>>> myRecoveredIndex = json.loads(output)
>>> list(myRecoveredIndex.keys())
['format-free', 'incorporating', 'function,', 'understand', 'augmented', '411)']
>>> 

あなたが提案したフォーマットが重要である場合は、あなたのフォーマットに従って自分でファイルを書くことができます。これを行う方法の提案は次のとおりです。

with open("myfile.txt", "w") as fstream:
    for key, data in myIndex.items():
        fstream.write("'{}': {!s}\n".format(key, data))
于 2013-11-12T20:37:22.273 に答える