2013-04-04 42 views
0

我目前正在嘗試編寫一個可以反映語句的基本「AI」。例如,如果用戶輸入「我的貓是棕色的」。 AI會返回「你的貓是棕色的?」如何在Python中替換字符串中的單詞?

我已經寫了可變數據的表,我打算使用的翻譯:

reflections = \ 
[["I",   "you"], 
["i",   "you"], 
["We",   "you"], 
["we",   "you"], 
["We're",  "you're"], 
["we're",  "you're"], 
["I'm",  "you're"], 
["i'm",  "you're"], 
["im",   "you're"], 
["this",  "that"], 
["This",  "that"], 
["am",   "are"], 
["Am",   "are"], 
["My",   "your"], 
["my",   "your"], 
["you",  "I"], # Grammar: Sometimes "me" is better 
["You",  "I"], 
["u",   "me"], 
["I'd",  "you'd"], 
["I'll",  "you'll"], 
["We'd",  "you'd"], 
["we'd",  "you'd"], 
["We'll",  "you'll"], 
["we'll",  "you'll"], 
["You're",  "I'm"], 
["you're",  "I'm"], 
["ur",   "I'm"], 
["c",   "see"], 
["I've",  "you've"], 
["We've",  "you've"], 
["we've",  "you've"], 
["Our",  "your"], 
["our",  "your"], 
["was",  "were"], 
["Was",  "were"], 
["were",  "was"], 
["Were",  "was"], 
["me",   "you"], 
["your",  "my"], 
["Your",  "my"]] 

不過,我有一些麻煩,實現數據。

我給串反射的電流定義爲:

from string import maketrans 

intab = ".!" 
outtab = "??" 
translate_message = maketrans(intab, outtab) #used to replace punctuation 

def reflect_statement(message): 
    if ' ' not in message: 
     if len(message) == 0: 
      return elicitations[0] 
     if len(message) == 1: 
      return elicitations[1] 
     if len(message) == 2: 
      return elicitations[2] 
     if len(message) == 3: 
      return elicitations[3] 
     if len(message) == 4: 
      return elicitations[4] 
     if len(message) == 5: 
      return elicitations[5] 
     if len(message) == 6: 
      return elicitations[6] 
     if len(message) == 7: 
      return elicitations[7] 
     if len(message) == 8: 
      return elicitations[8] 
     if len(message) == 9: 
      return elicitations[9] 
     if len(message) == 10: 
      return elicitations[10] 
     if len(message) > 10: 
      return elicitations[11] 
    if ' ' in message: 
     message = message.translate(translate_message) 
     return message 

忽略啓發參考,這是我已經完成了節目的一個獨立部分。

我真的很感謝別人可以給我提供的任何幫助。

乾杯!

+1

如果len(消息)==我: 回報的啓發[I] – zod 2013-04-04 21:27:05

回答

1
if ' ' not in message: 
    if len(message) < 11: 
     return elicitations[len(message)] 
    else: 
     return elicitations[11] 
else: 
    for pair in reflections: 
     message = message.replace(*pair) 

注:

  1. 這將取代部分單詞。要做出正確的替換,你需要精心製作一個正則表達式。也許像r'\b{}\b'.format(oldword)會的工作,但我不知道:

    import re 
    for old, new in reflections: 
        message = re.sub(r'\b{}\b'.format(old), new, message) 
    
  2. 嵌套表是不是最合理的數據結構,可以考慮使用字典。

+0

雖然它可能無法正常工作運非常想如何爲' 「我有一件禮物」''變成 「你有gyouft」' – 2013-04-04 21:30:39

+0

@JoranBeasley你是對的,我正在打字。 – 2013-04-04 21:31:22

+0

我認爲他需要一個語法來識別英語句子結構... – 2013-04-04 21:35:11

1

你真正想要做的是定義一個語法,這樣你可以挑出來的代名詞,然後只更換代名詞....

基本上是這樣的事情,你需要創建無語法不管是什麼......或者你的AI將永遠ammount的到太多東西

看看Neds List Of PyParsers ...我傾向於喜歡層

相關問題