【问题标题】:How to generate *.dict and *.idx file in python?如何在 python 中生成 *.dict 和 *.idx 文件?
【发布时间】:2020-10-13 15:35:22
【问题描述】:

基本上我已经在 python 中创建了一个字典,比如说

dictionary = {'test': [1, 2, 3], 'other': [100]} 

但我现在想编写一个程序,该程序将生成一个包含字典的 dict 文件(比如 file1.dict)和一个包含其倒排索引发布的 idx 文件(比如 file2.idx)。

【问题讨论】:

  • 据我所知,这些不是标准文件格式(至少在这种情况下 - .idx 是电影的字幕,.dict 是虚拟机的翻译!),你打算在里面放什么?
  • 请举例说明所需的输出。描述太模糊了。
  • 嘿,看看我的回答

标签: python dictionary indexing


【解决方案1】:

我建议对您要存储的任何对象使用.json 格式。为此,您可以导入 json 库,然后使用 json.dump 存储对象并使用 json.load 将其取回。

如果您想稍微弄乱格式,可以使用返回字符串的json.dumps,然后更改该字符串中您想要的任何内容并将其写入文件。

我不建议使用您描述的文件格式,因为它们不像其他人提到的那样标准。

【讨论】:

    【解决方案2】:

    首先使用以下代码创建文件- 注意:由于 .dict 和 .idx 不是我使用的标准扩展名 .txt

    dict_file = open("sample.txt", "w+")
    idx_file = open("sample.txt", "w+")
    

    现在用它写一些东西-

    dict_file.write(#pass the dictionary in it)
    idx_file.write(#pass the inverted index)
    

    最后添加以下代码关闭它-

    dict_file.close()
    idx_file.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      相关资源
      最近更新 更多