简体   繁体   English

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

[英]How to replace next word after a specific word in python

I have a string like below. 我有一个像下面的字符串。 Here, I want to replace just next immediate word after a particular word like, '%(db_user)s' and '%(db_passsword)s' but the words I can search for in the string are --db-user and --db-passwords becuase the above will be substituted by values. 在这里,我想替换一个特定单词之后的下一个直接单词,例如'%(db_user)s'和'%(db_passsword)s',但我可以在字符串中搜索的单词是--db-user和 - db-passwords因为上面的内容将被值替换。

Input: 输入:

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

Output: 输出:

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

So please help me with a function where I will provide an array of words and a string, which will replace next words to those supplied words. 所以请帮我一个函数,我将提供一个单词和一个字符串,它将替换那些提供的单词的下一个单词。

This will help - 这会有所帮助 -

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))

You could use insert here. 你可以在这里使用insert You would .split() your intial string to make it a list . 你会.split()你的初始string使它成为一个list Then you would insert into the position one after the index of the word you are searching. 然后你将insert到你正在搜索的单词index之后的位置。 After ' '.join() the list back into a string . ' '.join()list返回一个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'

a function where I will provide an array of words and a string, which will replace next words to those supplied words. 我将提供一个单词和一个字符串的函数,它将替换那些提供的单词的下一个单词。

Using general string processing 使用一般字符串处理

The following solution leverages Python's list.index method which is great to find stuff in well-formatted strings, short of using regexp. 以下解决方案利用了Python的list.index方法,这非常适合在格式良好的字符串中查找内容,而不是使用regexp。

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)

This works by first splitting the input string into words, then for each key/value pair in argmap find the index of the key and replace the existing word at index + 1 by the respective value. 这首先将输入字符串拆分为单词,然后对于argmap中的每个键/值对,找到键的索引,并将index + 1处的现有单词替换为相应的值。

We can use the replace_cmdargs function as follows 我们可以使用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'"

Note: This assumes the string is well-formatted, ie there is only one space between the key and the value to be replaced and there is always a corresponding string value. 注意:这假设字符串格式正确,即键和要替换的值之间只有一个空格,并且始终存在相应的字符串值。

Leveraging Python's built-in string formatting 利用Python的内置字符串格式

Since we already have a well-formatted string with format instructions in it, we could of course also use Python's built-in string formatting operator, no extra function needed: 由于我们已经有一个格式良好的字符串,其中包含格式指令,我们当然也可以使用Python的内置字符串格式化操作符,不需要额外的功能:

cmdargs % { 'db_user': 'MYUSER', 'db_password': 'MYPASS'}
=> "--db-user 'MYUSER' --db-password 'MYPASS'"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM