#! /usr/bin/env python # -*- coding: utf-8 -*- import re import codecs import random fin = codecs.open("2gram.txt","r","utf-8") fout = codecs.open("out_markov.txt","w","utf-8") message = raw_input("あなた:") message = message.decode("utf-8") number = random.randint(0,len(message)-1) startch = message[number].encode("utf-8") filearray = [] for line in fin: filearray.append(line) def calcarr(ch): arr = [] #arrは開始文字を先頭に含む2-gramのリスト。重複あり。 for line in filearray: if (line[0] == ch.decode("utf-8")): num = int(str(line[2:])) for x in range(num): arr.append(line[0:2]) return arr def nextstr(array): return array[random.randint(0,len(array)-1)][1] #2番目の文字を乱数を使って返す #ch = raw_input("文字を入力してください: ") #print calcarr(ch) sent = [startch] #初期化 開始文字の次の文字をリストに付加する #startch = startch.encode("utf-8") n = nextstr(calcarr(startch)) sent.append(n) n = n.encode('utf-8') n.strip() #print "type of startch: ",type(startch) #print "type of n: ",type(n) #print "n:",n #print "次の配列:",calcarr(n) while (n != "。"): #終端記号にならない限り繰り返す nextarray = calcarr(n) #print "計算された2-gramリスト",nextarray n = nextstr(nextarray) n = n.encode('utf-8') #print "確率的にとる次の文字",n sent.append(n) if(len(sent) >=20): break print "人工知能:", for s in sent: print s, fin.close() fout.close()
我慢だ。ていうのがうけた