本文整理汇总了Python中pymarkovchain.MarkovChain.generateString方法的典型用法代码示例。如果您正苦于以下问题:Python MarkovChain.generateString方法的具体用法?Python MarkovChain.generateString怎么用?Python MarkovChain.generateString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymarkovchain.MarkovChain
的用法示例。
在下文中一共展示了MarkovChain.generateString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BeerMarkov
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
class BeerMarkov():
def __init__(self, reviews_file, markov_dir):
self._reviews_file = reviews_file
self._markov_dir = markov_dir
self._markov = MarkovChain(markov_dir + '/beer_desc')
self._name_markov = MarkovChain(markov_dir + '/beer_name')
self.refresh_database()
def refresh_database(self):
with open(self._reviews_file, 'r') as review_data:
reviews = json.load(review_data)
reviews_string = [r['desc'] for r in reviews]
names_string = [r['name'] for r in reviews]
new_markov = MarkovChain(self._markov_dir + '/beer_desc')
new_markov.generateDatabase(' '.join(reviews_string))
new_name_markov = MarkovChain(self._markov_dir + '/beer_name')
new_name_markov.generateDatabase('.'.join(names_string))
self._markov = new_markov
self._name_markov = new_name_markov
def get_review(self):
return self._markov.generateString() + '. ' + \
self._markov.generateString()
示例2: markov
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def markov(messages):
# Create an instance of the markov chain. By default, it uses MarkovChain.py's location to
# store and load its database files to. You probably want to give it another location, like so:
mc = MarkovChain("./markov")
# To generate the markov chain's language model, in case it's not present
# mc.generateDatabase("\n".join(messages))
# To let the markov chain generate some text, execute
for i in xrange(100):
print mc.generateString()
示例3: Michiov
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
class Michiov(object):
def __init__(self, autogen=True, markovdb=os.path.expanduser("~/markov"), twcreds=os.path.expanduser("~/.michiov_twitter_credentials"),twappcreds=os.path.expanduser("~/.michiov_twitter_appdata")):
self.mc = MarkovChain(markovdb)
self.reload()
if not os.path.exists(twappcreds):
print("Lack of app creds")
sys.exit(1)
twcons = json.loads(open(twappcreds).read())
conskey = twcons['key']
conssec = twcons['secret']
while not os.path.exists(twcreds):
twitter.oauth_dance("MPRZ Tech Labs", conskey, conssec, twcreds)
oauth_token, oauth_secret = twitter.read_token_file(twcreds)
self.t = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, conskey, conssec))
def should(self):
ret = input("Should I send it? (y/N) ")
return ("y" in ret or "Y" in ret)
def qas(self):
idea = self.mc.generateString()
print("Generated: %s" % idea)
if self.should():
self.t.statuses.update(status=idea)
def loop(self):
try:
while True:
self.qas()
#self.reload()
except KeyboardInterrupt:
pass
def reload(self):
with open("markovpredb.txt") as file:
self.mc.generateDatabase(file.read())
示例4: markov
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def markov(msg, botName, channel, db):
if msg.rawMatchRe('!markov (?P<source>#?[a-zA-Z]\S*)\s*$') or msg.rawMatchRe('what (would|does) (the )?(?P<source>#?[a-zA-Z]\S+) say\??'):
m = msg.getRegExpResult()
source = m.group('source')
if source[0] == '#':
logsList = db.getLogs(chan=source, lines=2000)
else:
logsList = db.getLogs(nick=source, lines=2000)
if len(logsList) < 100:
hexchat.command("msg %s Not enough data for %s" % (channel, source))
else:
mc = MarkovChain("./markov_db")
ircText = ''
for line in logsList:
# disqualify lines that are too short or are certain bot functions that start with '!'
if len(line.split(' ')) >= 5 and line[0] != '!':
ircText += line.replace('.','') + '. '
mc.generateDatabase(ircText)
markovOutput = mc.generateString().capitalize()
hexchat.command('msg %s "%s" --%s' % (channel, markovOutput, source))
return True
return False
示例5: __init__
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
class TextGenerator:
def __init__(self, generatorName, trainString, prefixLength):
self.generatorName = generatorName
self.chain = MarkovChain()
self.chain.generateDatabase(trainString, n=prefixLength)
self.currState = []
self.hyphenator = Hyphenator('en_US')
self.syllableQ = Queue()
self.stripPattern = re.compile('[\W_]+')
while (len(self.currState) < prefixLength):
self.currState = self.chain.generateString().split()[-(prefixLength+1):-1]
def load_next_word(self):
nextword = ""
try:
while nextword == "":
nextword = self.stripPattern.sub('', self.chain._nextWord(self.currState))
self.currState = self.currState[1:]
self.currState.append(nextword)
if len(nextword) < 4: # because hyphenator doesnt work for words less than 4 letters
self.syllableQ.put(nextword)
else:
for syllable in self.hyphenator.syllables(nextword):
self.syllableQ.put(syllable)
except UnicodeEncodeError:
print("unicode error")
def get_next_syllable(self):
if (self.syllableQ.empty()):
self.load_next_word()
return self.syllableQ.get()
示例6: fetch_lyrics
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def fetch_lyrics(artist, lines):
API_KEY = os.environ.get('API_KEY')
uri = "http://api.lyricsnmusic.com/songs"
params = {
'api_key': API_KEY,
'artist': artist,
}
response = requests.get(uri, params=params)
lyric_list = response.json()
lyrics = ''
for lyric_dict in lyric_list:
lyrics += lyric_dict['snippet'].replace('...', '') + ' '
# Generate a Markov model
mc = MarkovChain('./markov')
mc.generateDatabase(lyrics)
# Add lines of lyrics
result = []
for line in range(0, lines):
line_string = mc.generateString()
result.append(line_string)
return result
示例7: lyrics
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def lyrics():
artist = request.form['artist']
lines = int(request.form['lines'])
if not artist:
return redirect(url_for('index'))
# Get a response of sample lyrics from the provided artist
uri = "http://api.lyricsnmusic.com/songs"
params = {
'api_key': API_KEY,
'artist': artist,
}
response = requests.get(uri, params=params)
lyric_list = response.json()
# Parse results into a long string of lyrics
lyrics = ''
for lyric_dict in lyric_list:
lyrics += lyric_dict['snippet'].replace('...', '') + ' '
# Generate a Markov model
mc = MarkovChain()
mc.generateDatabase(lyrics)
result = []
for line in range(0, lines):
result.append(mc.generateString())
return render_template('lyrics.html', result=result, artist=artist)
示例8: __init__
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
class EuroMarkov:
def __init__(self):
self.mc = MarkovChain("./markovdata")
def generateCountryList(self):
countryList = []
for filename in os.listdir("json_lyrics/2015"):
countryList.append(os.path.splitext(filename)[0])
return countryList
def loadFiles(self,startYear,endYear,countryList):
model = ""
for year in range(startYear,endYear+1):
for country in countryList:
fname = "json_lyrics/"+str(year)+"/"+country+".json"
if os.path.isfile((fname)):
with open (fname,"r") as myfile:
data = json.load(myfile)
model += (data['lyrics']) + '\n';
return model
def runMarkov(self,model):
self.mc.generateDatabase(model)
def generateString(self):
return self.mc.generateString()
示例9: Haley
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
class Haley(object):
def __init__(self, backend):
self.backend = backend
self.mc = MarkovChain("markov.db")
def loop(self):
self.backend.connect()
while True:
for event in self.backend.update():
try:
if event["type"] == "text":
times = re.search(r"(?P<nm>\d+) times", event["content"].lower())
if times:
if int(times.group("nm")) > 0:
times = min(5,int(times.group("nm")))
else:
self.backend.say("Okay, I won't say anything... Baka.")
continue
else:
times = 1
for i in range(times):
if "hi" in detox(event["content"].lower()).split() or "hello" in detox(event["content"].lower()).split():
self.backend.say(random.choice(["%s! Tutturuuu!","Hello, %s, so it was you making the noise up there!"]) % event["by"])
continue
if "nano" in event["content"].lower() or "hakase" in event["content"].lower():
self.backend.say("%s%s"%("HAKASE"*len(re.findall("nano", event["content"].lower())),"NANO"*len(re.findall("hakase", event["content"].lower()))))
continue
if event["mentioned"]:
if "roll" in detox(event["content"].lower()).split():
numb = re.search(r"(d|k)(?P<nm>\d+)", event["content"].lower())
if numb and int(numb.group("nm")) > 0:
self.backend.say("Aaaand... %d!" % (random.randrange(1,int(numb.group("nm"))+1)))
continue
else:
self.backend.say("Who do you think you are, rolling impossible dice... Baka.")
continue
if "say" in detox(event["content"].lower()).split():
if "something" in detox(event["content"].lower()).split():
tosay = self.mc.generateString()
elif "name" in detox(event["content"].lower()).split():
tosay = self.backend.get_name(event["by"])
self.backend.say(tosay)
continue
if "xkcd" in detox(event["content"].lower()).split():
if "random" in detox(event["content"].lower()).split():
x = xkcd.getRandomComic()
else:
numb = re.search(r"(?P<nm>\d+)", event["content"])
if numb:
x = xkcd.Comic(int(numb.group("nm")))
else:
x = xkcd.getLatestComic()
self.backend.say("*%s* - %s - _%s_" % (x.getTitle(), x.getImageLink(), x.getAltText()))
continue
self.backend.say("Hmm?")
continue
except:
self.backend.say(str(sys.exc_info()[0]))
示例10: markov
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def markov():
"""A simple markov function"""
mc = MarkovChain("./tempchain")
with open(CORPUS, 'r') as f:
data = f.read()
mc.generateDatabase(data)
return mc.generateString()
示例11: main
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def main():
args = parser.parse_args()
dirname=os.path.split(__file__)[0]
filename=os.path.join(dirname,"phil.txt")
title_filename=os.path.join(dirname,"phil_titles.txt")
dbname1 = "database.pkl"
dbname2 = "database_title.pkl"
new_db = not os.path.exists(dbname1)
body_maker = MarkovChain(dbname1)
title_maker = MarkovChain(dbname2)
if new_db:
title_maker.generateDatabase(open(title_filename).read())
title_maker.dumpdb()
body_maker.generateDatabase(open(filename).read())
body_maker.dumpdb()
name = title_maker.generateString()
body = ' '.join([body_maker.generateString()+'.' for i in xrange(3)])
if args.repo:
if args.token:
token = args.token
else:
token_filename = os.path.join(dirname, "token.txt")
if not os.path.exists(token_filename):
sys.stderr.write("Please either specify --token=XXX on the command line or put a github API token in token.txt\n")
sys.stderr.write("You can generate a token here: https://github.com/settings/tokens\n")
sys.exit(1)
token = open(token_filename).read().strip()
import github
gh=github.Github(token)
user=gh.get_user()
repo=user.get_repo(args.repo)
issue = repo.create_issue(title=name, body=body)
print issue.html_url
else:
print
print name
print "-"*len(name)
print body
示例12: main
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def main(args):
markov_filename = "./" + args.subreddit + ".mcd"
new_chain = os.path.isfile(markov_filename) == False # this must come before the creation of the Markov Chain
mc = MarkovChain(markov_filename)
if args.new or new_chain:
titles = getTitles(getSubmissions(100, args.subreddit))
training_data = str.join('.', titles)
mc.generateDatabase(training_data)
N = args.num_submissions
while N > 0:
print(mc.generateString())
N -= 1
示例13: markovbuild
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
class markovbuild(object):
'''Builds a markov chain DB and outputs data'''
def __init__(self, target, data, lines=5):
self.database = '/tmp/markov_%s.db' % target
self.lines = lines
self.data = '\n'.join(data)
self.mchain = MarkovChain(self.database)
def build(self):
'''Builds a markov chain'''
self.mchain.generateDatabase(self.data)
def output(self):
'''Outputs markov chain data'''
self.build()
return [ self.mchain.generateString() for x in xrange(0, self.lines) ]
示例14: poem
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def poem():
story = str(request.form['story'].encode('ascii', 'ignore'))
lines = int(request.form['lines'])
if not story:
return redirect(url_for('index'))
mc = MarkovChain()
mc.generateDatabase(story)
result = []
for line in range(0, lines):
new_line = mc.generateString()
if new_line not in result:
result.append(new_line)
return render_template('poem.html', result=result, story=story)
示例15: analyze
# 需要导入模块: from pymarkovchain import MarkovChain [as 别名]
# 或者: from pymarkovchain.MarkovChain import generateString [as 别名]
def analyze(self):
# GenerateModel
""" Generate a Markov chain based on retrieved strings. """
mc = MarkovChain()
mc.generateDatabase(self.text)
result = r''
print "Generating:"
for i in range(0, 10):
print "Sentence %d" % i
# Create 10 sentences
sentence = mc.generateString()
result += sentence.capitalize() + '. '
return result