2012-12-16 44 views
-1

好了,所以我有以下的小功能:字符串代替單詞

def swap(inp): 
    inp = inp.split() 
    out = "" 

    for item in inp: 
     ind = inp.index(item) 
     item = item.replace("i am", "you are") 
     item = item.replace("you are", "I am") 
     item = item.replace("i'm",  "you're") 
     item = item.replace("you're", "I'm") 
     item = item.replace("my",  "your") 
     item = item.replace("your", "my") 
     item = item.replace("you",  "I") 
     item = item.replace("my",  "your") 
     item = item.replace("i",  "you") 
     inp[ind] = item 

    for item in inp: 
     ind = inp.index(item) 
     item = item + " " 
     inp[ind] = item 

    return out.join(inp) 

,雖然它不是特別有效獲得更短的句子完成任務。基本上,它所做的只是交換代詞等觀點。這是很好,當我拋出一個字符串,如「我愛你」吧,它會返回「你愛我」,但是當我扔東西,如:

you love your version of my couch because I love you, and you're a couch-lover. 

我得到:

I love your versyouon of your couch because I love I, and I'm a couch-lover. 

我我很困惑爲什麼會發生這種情況。我明確地將字符串分割成一個列表來避免這種情況。爲什麼它能夠將其檢測爲列表項的一部分,而不僅僅是完全匹配?

此外,稍微偏離,以避免不得不張貼另一個如此相似的問題;如果解決方案打破了這個功能,逗號,句號和其他標點符號會發生什麼?

它犯了一些非常令人驚訝的錯誤。我的預期成果是:

I love my version of your couch because you love I, and I'm a couch-lover. 

我格式化像這樣的原因,是因爲我希望最終能夠取代item.replace用字(X,Y)的變量在數據庫中。

+1

您可能必須將它拆分到列表,但「版本」將是那些列表中的元素之一,然後你在它取代「我」與「你」 ... –

回答

1

對於這個特定的問題,你需要正則表達式。基本上,沿着線:

table = [ 
    ("I am", "you are"), 
    ("I'm", "you're"), 
    ("my", "your"), 
    ("I", "you"), 
] 

import re 

def swap(s): 
    dct = dict(table) 
    dct.update((y, x) for x, y in table) 
    return re.sub(
     '|'.join(r'(?:\b%s\b)' % x for x in dct), 
     lambda m: dct[m.group(0)], 
     s) 

print swap("you love your version of my couch because I love you, and you're a couch-lover.") 
# I love my version of your couch because you love I, and I'm a couch-lover. 

但在一般情況下,自然語言處理的字符串的手段/重功能是幼稚充其量(注意:「你愛我」以上)。

1

繼承人一個簡單的代碼:

def swap(inp): 
    inp = inp.split() 
    out = [] 
    d1 = ['i am', 'you are', 'i\'m', 'you\'re', 'my', 'your', 'I', 'my', 'you'] 
    d2 = ['you are', 'I am', 'you\'re', 'I\'m', 'your', 'my', 'you', 'your', 'I'] 
    for item in inp: 
     itm = item.replace(',','') 
     if itm not in d1: 
      out.append(item) 
     else: out.append(d2[d1.index(itm)]) 
    return ' '.join(out) 

    print(swap('you love your version of my couch because I love you, and you\'re a couch-lover.'))