替换字符串中的单词

时间:2012-12-16 10:51:02

标签: python list replace python-2.7 python-2.x

好的,所以我有以下小功能:

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)变量。

3 个答案:

答案 0 :(得分:2)

对于此特定问题,您需要正则表达式。基本上,沿着:

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.

但总的来说,通过字符串/ re函数进行自然语言处理最多是天真的(注意上面的“你爱我”)。

答案 1 :(得分: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.'))

答案 2 :(得分:0)

问题是index()replace()都适用于子字符串(在您的情况下,是子字词)。

看看我对另一个问题的回答:String replacement with dictionary, complications with punctuation

该答案中的代码可用于解决您的问题。

相关问题