使用python进行锅炉板文本

时间:2015-03-17 14:44:17

标签: python text io

在我的应用程序中,我希望能够在多行textctrl

中显示预定义的段落

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

有人能建议以这种形式保存和检索文本的合适方式吗?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我建议使用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()

答案 2 :(得分:0)

看看使用sqlite3,我相信它非常适合您的需求,而无需轻松下载完整的数据库路径。 以下是创建数据库的命令行中的示例,使用键和一些文本填充它然后打印出内容。用于sqlite3的python编码很简单,并且有很好的文档记录。

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