如何将我创建的索引写入Python中的文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何将我创建的索引写入Python中的文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2092字,纯文字阅读大概需要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.
解决方法:
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中的文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。