0

i have this code:

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"]

i wan to replace:

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

the output should be:

 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

Thank you!

I have tried this:

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

but i got this error : 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

尝试查看链接理解

word = [words.replace('the','THE') for words in word];
于 2013-08-19T09:28:08.337 回答
0

x是一个字符串。并使用x .replace("X","Y")。(用 Y 代替 X)。

于 2013-08-19T09:16:41.180 回答