[英]Replacing words in a sentence from database (Python/Django)
我有一個這樣的字符串句子結構:
從$ Duration%開始,$ Noun $將為$ Adjective $
我需要查看哪些單詞在“ $$”中,並用從SQL文件導入的數據庫中的隨機單詞替換它們。
這是模型/ sql文件:
from django.db import models
from django.utils import timezone
class Type(models.Model):
type = models.CharField(max_length=50)
value = models.CharField(max_length=1)
class Word(models.Model):
dict = models.CharField(max_length=200)
kind = models.CharField(max_length=1)
def randword(self):
words = self.objects.all()
number = randrang(0,len(words))
return words[number]
class Question(models.Model):
question = models.CharField(max_length=200)
def randquest(self):
quests = self.objects.all()
numbeq = randrang(0, len(quests))
return quests[numbeq]
class Meta(models.Model):
question = models.ForeignKey(Question)
score = models.ForeignKey("Score")
user = models.CharField(max_length=200)
time = models.DateTimeField('date published')
class Score(models.Model):
word = models.ForeignKey(Word)
score = models.IntegerField()
question = models.ManyToManyField(Question, through=Meta)
def __unicode__(self):
return self.score
SQL文件
INSERT INTO quest_question (question) VALUES ('Starting in $Duration$, the $Noun$ will be $Adjective$');
和
INSERT INTO quest_word (dict, kind) VALUES ('Coffee Maker', '1');
INSERT INTO quest_word (dict, kind) VALUES ('24 hours', '3');
INSERT INTO quest_word (dict, kind) VALUES ('today', '3');
INSERT INTO quest_word (dict, kind) VALUES ('broken', '2');
INSERT INTO quest_word (dict, kind) VALUES ('Email server', '1');
INSERT INTO quest_word (dict, kind) VALUES ('15 minutes', '3');
INSERT INTO quest_word (dict, kind) VALUES ('tomorrow', '3');
INSERT INTO quest_word (dict, kind) VALUES ('unavailable', '2');
INSERT INTO quest_type (type, value) VALUES ('Noun', '1');
INSERT INTO quest_type (type, value) VALUES ('Adjective', '2');
INSERT INTO quest_type (type, value) VALUES ('Duration', '3');
我開始寫視圖。 需要一些幫助:
from quest.models import Word, Type, Score, Question, Meta
from django.utils import timezone
def question(request):
sentence = Question.objects.all()
find_words = re.findall(r"\w+%0-9a-zA-Z%", sentence.question)
如果您願意更改表示法,則有兩種選擇:
>>> 'Starting in {Duration}, the {Noun} will be {Adjective}'.format(Duration='24 hours', Noun='Coffee Maker', Adjective='broken') 'Starting in 24 hours, the Coffee Maker will be broken' >>> 'Starting in %(Duration)s, the %(Noun)s will be %(Adjective)s' % dict(Duration='24 hours', Noun='Coffee Maker', Adjective='broken') 'Starting in 24 hours, the Coffee Maker will be broken'
>>> from django.template import Context, Template >>> t = Template('Starting in {{Duration}}, the {{Noun}} will be {{Adjective}}') >>> c = Context(dict(Duration='24 hours', Noun='Coffee Maker', Adjective='broken')) >>> t.render(c) u'Starting in 24 hours, the Coffee Maker will be broken'
剩下的就是從數據庫中提取並隨機選擇單詞,這很容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.