简体   繁体   English

在不使用内置 python 函数的情况下替换字符串中的短语?

[英]Replacing phrases in string without using built-in python functions?

I'm trying to write a function to replace phrases that I have stored in a list with acronyms which are also stored in a list.我正在尝试编写 function 来用也存储在列表中的首字母缩写词替换我存储在列表中的短语。 Trying to do this without most built in functions.尝试在没有大多数内置函数的情况下执行此操作。 Here's my best attempt thus far:到目前为止,这是我最好的尝试:

    def replace_phrase(string):
        result = ''
        for i in range(len(string)):
            counter = 0
            for phrase in phrases_to_replace_list:
                if len(phrase) < len(string[i:]):
                    pass
                elif string[i:i + len(phrase)] == phrase:
                    pre = string[:i]
                    post = string[i + len(phrase):]
                    result += pre + replacement_phrases[counter] + post
                counter += 1
        return result

With a string of "Oh my god I love you got to go" an output of "OMG ILY GTG" is what I'm trying to achieve, but the code is outputting "Oh my god I love you GTG" .有一串"Oh my god I love you got to go""OMG ILY GTG"output是我想要实现的,但代码输出的是"Oh my god I love you GTG"

However In your post there is no Logic for space between OMG and ILY and GTG .但是,在您的帖子中, OMGILYGTG之间没有space逻辑。

So just assume that there may group of three char.所以只是假设可能有三个字符组。

You may try below code:您可以尝试以下代码:

def replace_phrase(string):
  result =''
  flag=True
  cnt=3
  for c in string.strip():
    if c==' ':
      flag=True
      continue
    if flag==True:
      cnt+=1
      result=result+c.upper()
      if cnt%3==0:
        result=result+' '
      flag=False     
  return result

print(replace_phrase('Oh my god I love you got to go'))

Output: Output:

OMG ILY GTG

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

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