使用 python 作为样板文本

Using python for boiler plate text

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

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

任何人都可以建议一种合适的方式来保存和检索这种形式的文本吗?

将文本保存在文本文件中,使用 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...",
...}

我建议使用 pickle。它比 json 更快,更酷的将内容保存到文件的方式。

Warning The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

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

看看使用 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>