2015-04-16 149 views
-1

我該如何將它移植到Python 3?移植到Python 3問題

import random 

class Markov(object): 

    def __init__(self, open_file): 
     self.cache = {} 
     self.open_file = open_file 
     self.words = self.file_to_words() 
     self.word_size = len(self.words) 
     self.database() 
#  self.open_file.close() 
#  del self.open_file  

    def file_to_words(self): 
     self.open_file.seek(0) 
     data = self.open_file.read() 
     words = data.split() 
     return words 


    def triples(self): 
     """ Generates triples from the given data string. So if our string were 
       "What a lovely day", we'd generate (What, a, lovely) and then 
       (a, lovely, day). 
     """ 

     if len(self.words) < 3: 
      return 

     for i in range(len(self.words) - 2): 
      yield (self.words[i], self.words[i+1], self.words[i+2]) 

    def database(self): 
     for w1, w2, w3 in self.triples(): 
      key = (w1, w2) 
      if key in self.cache: 
       self.cache[key].append(w3) 
      else: 
       self.cache[key] = [w3] 

    def generate_markov_text(self, size=20): 
     seed = random.randint(0, self.word_size-3) 
     seed_word, next_word = self.words[seed], self.words[seed+1] 
     w1, w2 = seed_word, next_word 
     gen_words = [] 
     for i in xrange(size): 
      gen_words.append(w1) 
      w1, w2 = w2, random.choice(self.cache[(w1, w2)]) 
     gen_words.append(w2) 
     return ' '.join(gen_words) 

我知道我可以自己做,但我不知道如何。在Python 3中未定義xrange。我應該將其更改爲?

+2

將'xrange'更改爲'range' – EdChum

+0

請參閱https://docs.python.org/3/howto/pyporting.html – jonrsharpe

+0

您是否通過2to3運行代碼以查看它是否提供任何警告或其他更改? – TheBlackCat

回答

0

在python3中,xrange運算符被重命名爲範圍(刪除舊範圍),因此應該修改以解決您的問題。否則,功能是相同的。