【问题标题】:Using python for boiler plate text [closed]将python用于样板文本[关闭]
【发布时间】:2015-03-17 14:44:16
【问题描述】:

在我的应用程序中,我希望能够在多行 textctrl 中显示预定义的段落

我假设文本将保存在一个文本文件中,我想通过提供一个密钥来访问它;例如,在键 101 下保存的文本可能有几段与狮子有关,而在键 482 下可能有几段与海狮的食物有关。

谁能建议一种合适的方式来保存和检索此表单中的文本?

【问题讨论】:

  • 更具体地说,您可以将文本段落存储在以数字为键的字典中,并使用我对问题 How to save an object in Python 的基于泡菜的答案进行保存。

标签: python text io


【解决方案1】:

看看使用 sqlite3,我相信它非常适合您的需求,而无需走完整的数据库路线。 这是一个创建数据库的命令行示例,用一个键和一些文本填充它,然后打印出内容。在 python 中为 sqlite3 编写代码非常简单且有据可查。

$ sqlite3 text.db
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> CREATE TABLE "txt" ("txt_id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE  DEFAULT 1, "the_text" TEXT);

sqlite> insert into txt ("txt_id","the_text") values (1,"a great chunk of text");

sqlite> insert into txt ("txt_id","the_text") values (2,"Elephants are large mammals of the family Elephantidae and the order Proboscidea. Two species are traditionally recognised, the African elephant (Loxodonta africana) and the Asian elephant (Elephas maximus), although some evidence suggests that African bush elephants and African forest elephants are separate species (L. africana and L. cyclotis respectively). Elephants are scattered throughout sub-Saharan Africa, South Asia, and Southeast Asia. Elephantidae are the only surviving family of the order Proboscidea; other, now extinct, families of the order include mammoths and mastodons. Male African elephants are the largest surviving terrestrial animals and can reach a height of 4 m (13 ft) and weigh 7,000 kg (15,000 lb). All elephants have several distinctive features the most notable of which is a long trunk or proboscis, used for many purposes, particularly breathing, lifting water and grasping objects. Their incisors grow into tusks, which can serve as weapons and as tools for moving objects and digging. Elephants' large ear flaps help to control their body temperature. Their pillar-like legs can carry their great weight. African elephants have larger ears and concave backs while Asian elephants have smaller ears and convex or level backs.");

sqlite> select * from txt;

1|a great chunk of text

2|Elephants are large mammals of the family Elephantidae and the order Proboscidea. Two species are traditionally recognised, the African elephant (Loxodonta africana) and the Asian elephant (Elephas maximus), although some evidence suggests that African bush elephants and African forest elephants are separate species (L. africana and L. cyclotis respectively). Elephants are scattered throughout sub-Saharan Africa, South Asia, and Southeast Asia. Elephantidae are the only surviving family of the order Proboscidea; other, now extinct, families of the order include mammoths and mastodons. Male African elephants are the largest surviving terrestrial animals and can reach a height of 4 m (13 ft) and weigh 7,000 kg (15,000 lb). All elephants have several distinctive features the most notable of which is a long trunk or proboscis, used for many purposes, particularly breathing, lifting water and grasping objects. Their incisors grow into tusks, which can serve as weapons and as tools for moving objects and digging. Elephants' large ear flaps help to control their body temperature. Their pillar-like legs can carry their great weight. African elephants have larger ears and concave backs while Asian elephants have smaller ears and convex or level backs.

sqlite> 

【讨论】:

    【解决方案2】:

    将文本保存在文本文件中,使用open() 打开它,然后使用read() 读取结果。

    例如:

    TEXT_DIRECTORY = "/path/to/text"
    def text_for_key(key):
        with open(os.path.join(TEXT_DIRECTORY), str(key)) as f:
            return f.read()
    

    或者,如果您更喜欢一个大文件而不是许多小文件,只需将其存储为 JSON 或其他一些易于阅读的格式:

    import json
    with open("/path/to/my/text.json") as f:
       contents = json.load(f)
    
    def text_for_key(key):
        return contents[key]
    

    那么您的文件将如下所示:

    {101: "Lions...",
     482: "Sea lions...",
    ...}
    

    【讨论】:

    • 谢谢布赖恩。我试试json吧
    • 我推荐使用pickle (docs.python.org/2/library/pickle.html),因为它更快更酷:)。但您需要记住:pickle 模块并非旨在防止错误或恶意构造的数据。永远不要解开从不受信任或未经身份验证的来源收到的数据。
    • @Lukas 是的,但它不容易编辑,你需要添加单独的工具来写出你的文件。如果您真的需要额外的速度,并且不介意无法从其他语言读取或写入它,那很好,但是 JSON 随处可用,并且人类可读和可编辑。从最简单到最复杂,我只对普通的平面文件、JSON、pickle、一个真正的单进程数据库(如 SQLite)和一个真正的多用户数据库(如 PostgreSQL)进行排名。对于所描述的用例,我建议留在该范围内更简单的一端,但所有选择都有其优点。
    【解决方案3】:

    我建议使用pickle。它比 json 更快,而且保存文件的方式更酷。

    警告 pickle 模块并非旨在防止 错误或恶意构建的数据。永远不要解压数据 从不受信任或未经身份验证的来源收到。

    import pickle
    import os
    
    class Database(object):
    
        def __init__(self, name='default'):
            self.name = '{}.data'.format(name)
            self.data = None
            self.read()
    
        def save(self):
            with open(self.name, 'wb') as f:
                self.data = pickle.dump(self.data, f)
    
        def read(self):
            if os.path.isfile(self.name):
                with open(self.name, 'rb') as f:
                    self.data = pickle.load(f)
            else:
                self.data = {}
    
        def set(self, key, value):
            self.data[key] = value
    
        def get(self, key):
            return self.data[key]
    

    用法:

    database = Database('db1')
    database.set(482, 'Sea lions...')
    print(database.get(482))
    database.save()
    

    【讨论】:

      猜你喜欢
      • 2011-07-17
      • 1970-01-01
      • 2014-10-10
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多