0

私はこのコードを持っています:

word = ["General William Shelton, said the system",
        "which will provide more precise positional data",
        "and that newer technology will provide more",
        "Commander of the Air Force Space Command",
        "objects and would become the most accurate metadata"]

交換したい:

Replace “the” with “THE”, “
Replace “William Shelton” with “AliBaba”
Replace “data” with “SAMSUNG”

出力は次のようになります。

 General AliBaba,said THE system which will provide more precise
 positional SAMSUNG and that newer technology will provide more
 Commander of the Air Force Space Command objects and would become the
 most accurate metadata

ありがとうございました!

私はこれを試しました:

rep_word = {"the":"THE", "William Shelton":"AliBaba", "system":"Samsung"}
replace = re.compile(r'\b(' + '|'.join(rep_word.keys()) + r')\b')
result = replace.sub(lambda x: rep_word[x.group()], word)
print result

しかし、私はこのエラーを受け取りました: TypeError: expected string or buffer

4

4 に答える 4

1

Pythonで構築された関数「reduce」を使用できると思います:

def change(prev, s):
     ret = s.replace("the", "THE")
     ret = ret.replace("William Shelton","AliBaba")
     ret = ret.replace("data", "SAMSUNG")
     return prev+' '+ret

reduce(change, word, '')
于 2013-08-19T09:30:09.587 に答える
1
import re
word = ["General William Shelton, said the system",
        "which will provide more precise positional data",
        "and that newer technology will provide more",
        "Commander of the Air Force Space Command",
        "objects and would become the most accurate metadata"]
replacements = [("the", "THE"), ("William Shelton", "AliBaba"), ("data", "SAMSUNG")]
compiled = [(re.compile(r'\b%s\b' % re.escape(s)), d) for s, d in replacements]
replaced = [reduce(lambda s,(regex,res): regex.sub(lambda _: res, s), compiled, w) for w in word]
result = ' '.join(replaced)
result
'General AliBaba, said THE system which will provide more precise positional SAMSUNG and that newer technology will provide more Commander of THE Air Force Space Command objects and would become THE most accurate metadata'
于 2013-08-19T09:23:50.723 に答える
0

xは文字列です。x .replace ("X","Y") を使用します。(X を Y に置き換えます)。

于 2013-08-19T09:16:41.180 に答える