Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

python - 用python中的占位符替换字符串(replace strings with placeholders in python)

I am trying to replace the variables with placeholders like XXX.

(我正在尝试使用XXX之类的占位符替换变量。)

The words "hello" and "morning" are printed as-is because they appear in another list.

(单词“ hello”和“ morning”按原样打印,因为它们出现在另一个列表中。)

The following code works, but prints extra placeholders.

(以下代码有效,但会打印出额外的占位符。)

import re

mylist = ['hello', 'morning']
nm = [
    "Hello World Robot Morning.",
    "Hello Aniket Fine Morning.",
    "Hello Paresh Good and bad Morning.",
]



def punctuations(string):
    pattern = re.compile(r"(?u)ww+")
    result = pattern.match(string)
    myword = result.group()
    return myword


for x in nm:
    newlist = list()
    for y in x.split():
        for z in mylist:
            if z.lower() == punctuations(y.lower()):
                newlist.append(y)
            else:
                newlist.append("xxx")
    print(newlist)

Output:

(输出:)

['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']
['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']
['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']

Expected output:

(预期产量:)

['Hello', 'xxx', 'xxx',  'Morning.']
['Hello', 'xxx', 'xxx',   'Morning.']
['Hello', 'xxx', 'xxx', 'xxx', 'xxx', 'Morning.']
  ask by shantanuo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to break when you have found the word and only after checking all the elements in my_list evaluate if you have found something, and if not, append the placeholder

(找到单词后,必须先检查my_list所有元素,然后才能判断是否找到了东西,否则必须附加占位符)

for x in nm:
    newlist = list()
    for y in x.split():
        found = False
        for z in mylist:
            if z.lower() == punctuations(y.lower()):
                newlist.append(y)
                found = True
                break
        if not found:
            newlist.append('xxx')
    print(newlist)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...