2015-12-14 67 views
-3

我在維基百科上閱讀了關於Article spinning的內容,我試圖創建一個從文本源執行相同操作的函數。使用python從文本源生成隨機註釋

例如文本源可能是:

{Hello|Hi|Howdy}{ ,I {really like|absolutely adore} your {picture|media|upload}|{, how are you?|, are you ok?}} 

一些能夠產生的隨機評論:

Hello, I really like your picture 
Hi, I absolutely adore your upload 
Hi, how are you? 
and so on... 

我的主要問題是讀括號內的字。我目前使用的文本正則表達式,但Python是隻考慮第一個和最後一個支架,所以這就是我得到:

Hello|Hi|Howdy}{ ,I {really like|absolutely adore} your {picture|media|upload}|{, how are you?|, are you ok?} 
+1

請出示你的代碼,否則我們無法真正幫助你多少。這似乎是一個經典的貪婪vs非貪婪的正則表達式問題 –

+2

-1垃圾郵件 – wim

回答

1

我自己做到了。

def pick_random_word(self, match): 
    words = match.group(1) 
    return random.choice(words.split("|")) 

def write_comment(self, comment): 
    r = re.compile('{([^{}]*)}') 
    while True: 
     comment, n = r.subn(self.pick_random_word, comment) 
     if n == 0: 
      break 
    print(comment) 

#USAGE: self.write_comment("{{so|totally} ugly|very {nice|bad}} {photo|media|upload} {:)||:D|<3}") 

它會打印:

totally ugly photo 
so ugly media :D 
very bad photo <3 
and so on... 
2
import random 

list_a = ['Hello', 'Hi', 'Howdy'] 
list_b = ['really like', 'absolutely adore'] 
list_c = ['picture', 'upload'] 

word_a = random.choice(list_a) 
word_b = random.choice(list_b) 
word_c = random.choice(list_c) 

print "{0}, I {1} your {2}.".format(word_a, word_b, word_c)