如何在Python中替换特定单词后的下一个单词

3

我有一个字符串,如下所示。在这里,我想替换特定单词后面的下一个单词,例如'%(db_user)s'和'%(db_passsword)s',但我可以在字符串中搜索的单词是--db-user和--db-passwords,因为上述内容将被值替换。

输入:

 "cd scripts &&   bash setup.sh  --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '%(db_user)s' --db-password '%(db_password)s' "

输出:

 "cd scripts &&   bash setup.sh  --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '***' --db-password '****' "

请帮我编写一个函数,我会提供一个单词数组和一个字符串,该函数将把下一个单词替换为提供的单词。


@mypetlion 哦,是的。 - U13-Forward
其实我不再需要它们了 :-) - U13-Forward
4个回答

3
这将有所帮助 -
import re

def char_index(sentence, word_index): 
    sentence = re.split('(\s)',sentence) #Parentheses keep split characters 
    return len(''.join(sentence[:word_index*2]))

def print_secure_message(msg):
    secure_words = ['--db-user', '--db-password']
    # Removing extra white spaces within string
    msg = re.sub(' +', ' ', msg)
    cpy_msg = msg.split(" ")
    for word in secure_words:
        # Getting index of the word's first characters
        t = re.search(word, msg)
        # Getting index of the next word of the searched word's
        word_index = cpy_msg.index(word)+2;
        index= char_index(msg, word_index)
        print(t.end(), word_index, index)
        msg = msg[0:t.end() + 1] + "'****'" + msg[index - 1:]
    print(''.join(msg))

这是问题的解决方案还是附加信息? - Sid
这是被问到的问题的解决方案。 - Rashmi Jain
在这种情况下,最好编辑问题本身。 - Sid

1
你可以在这里使用 insert 。您需要使用 .split() 将初始的 string 分割成 list。然后,您需要在搜索到的单词的 index 后面的位置进行 insert。最后,将修改后的 list' '.join() 转换回 string
s = "cd scripts &&   bash setup.sh  --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '%(db_user)s' --db-password '%(db_password)s' "

s = s.split()
a = '***'
b = '****'

s.insert((s.index('--db-user')+1), a)
s.insert((s.index('--db-password')+1), b)
s = ' '.join(s)
print(s)
# cd scripts && bash setup.sh --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user *** '%(db_user)s' --db-password **** '%(db_password)s'

是的,它正在运作,代码更短了,谢谢 @vash_the_stampede - Rashmi Jain

0
一个函数,我将提供一个单词数组和一个字符串,它将替换下一个单词为那些提供的单词。
使用通用字符串处理
以下解决方案利用Python的list.index方法,在不使用正则表达式的情况下查找格式良好的字符串中的内容。
def replace_cmdargs(cmdargs, argmap):
   words = cmdargs.split(' ')
   for arg, value in argmap.iteritems():
      index = words.index(arg)
      argname = words[index + 1].replace('%(', '').replace(')s', '').replace("'", '').replace('"', '')
      words[index + 1] = words[index + 1] % {argname: value}
   return ' '.join(words)

这个程序的实现方式是先将输入字符串分割成单词,然后对于argmap中的每个键/值对,在其中找到键的索引并用相应的值替换index + 1处的现有单词。

我们可以按以下方式使用replace_cmdargs函数

cmdargs = "--db-user '%(db_user)s' --db-password '%(db_password)s'"
replace_cmdargs(cmdargs, {
        '--db-user': 'MYUSER',
        '--db-password': 'MYPASS'
    })

=> "--db-user 'MYUSER' --db-password 'MYPASS'"

注意:这假设字符串格式良好,即要替换的键和值之间只有一个空格,并且始终存在相应的字符串值。
利用Python内置的字符串格式化
既然我们已经有了一个带有格式指令的格式良好的字符串,我们当然也可以使用Python的内置字符串格式化运算符,无需额外的函数:
cmdargs % { 'db_user': 'MYUSER', 'db_password': 'MYPASS'}
=> "--db-user 'MYUSER' --db-password 'MYPASS'"

0
根据vash_the_stampede的解决方案,这是一个通用解决方案。 如果有多个需要替换的密码实例,它也可以工作。
def clean_next_word(msg,words):

#choose your filler
filler="*****"

#isolate words in list
msg=msg.split(" ")

for word in words:

    #optional check
    if word in msg:
        
        #get all positions of key words
        indexes = []
        for i, num in enumerate(msg):  
            if num == word:  
                indexes.append(i)
        
        #replace by the filler
        for indexe in indexes:
            msg[indexe+1]=filler

return ' '.join(msg)

对于上述示例:
msg =  "cd scripts &&   bash setup.sh  --client-name %(client_name)s --is-db-auth-enabled %(is_db_auth_enabled)s --db-user '%(db_user)s' --db-password '%(db_password)s' "
words=['--db-user', '--db-password']
output=clean_next_word(msg,words)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接