gpt4 book ai didi

python - 如何在 Python 中将我创建的索引写入文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:21 24 4
gpt4 key购买 nike

我想知道如何将以下索引写入文件。下面的索引是从我创建的函数返回的。

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.

最佳答案

Pickle 的目的不是为了变得更好,而是将数据序列化到一个文件中,以便以后可以高效地反序列化它。其他模块,如 PrettyPrint模块旨在以一种很好的方式打印出 Python 数据。但是,如果您的目标是稍后能够反序列化数据,您可以查看 JSON格式及其 Python module

>>> 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))

关于python - 如何在 Python 中将我创建的索引写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19939163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com