简体   繁体   中英

String replacement using two lists - Python

Two lists were created through several operations.

a = ["Cat", "Dog", "Pigeon", "Eagle", "Camel"]
b = ["Tiger", "Bat", "Whale", "Snake", "Bear"]

I'm trying to replace a string using this list. (a) using a list to search for a word and (b) replacing it with a list. The order can be substituted in the same order as each list.

Each word is replaced with cat -> Tiger / Dog ->Bat / Pigeon -> Whale / Eagle -> Snake /Camel -> Bear in list order.

text = """
Cats and dogs live in our village. There are also pigeons and eagles. 
There are no camels.

Cats and dogs live in our village. There are also pigeons and eagles. 
There are no camels.

Cats and dogs live in our village. There are also pigeons and eagles. 
There are no camels.

.....

"""

The desired result is

text = """
Tigers and bats live in our village. There are also whales and snakes. 
There are no bears.

Tigers and bats live in our village. There are also whales and snakes. 
There are no bears.

Tigers and bats live in our village. There are also whales and snakes. 
There are no bears.

.....

"""

I've tried a number of other things besides this one, but to no avail. Help

new_text = []
num = 1
num1 = 1
for line in text.split('\n'):
    text = text.replace(a[num], b[num1])
    new_text.append(text)
    num += 1
    num1 += 1

try to loop all 2nd list and replace with 1st list .

for i in range(len(a)):
    if b[i] in text:
        text = text.replace(b[i],a[i])

Use str.replace in a loop, and since a and b are capitalized you'll need to do a separate replace operation for the lowercase version of each word:

>>> for x, y in zip(a, b):
...     text = text.replace(x, y)
...     text = text.replace(x.lower(), y.lower())
...
>>> print(text)

Tigers and bats live in our village. There are also whales and snakes.
There are no bears.

Tigers and bats live in our village. There are also whales and snakes.
There are no bears.

Tigers and bats live in our village. There are also whales and snakes.
There are no bears.

.....

Doing this in a completely generic way is tricky -- for example, would you translate cAt as tIger or tIGEr or tIgEr ? But mapping the original str.title() casing as well as the str.lower() casing is adequate for this particular input. For a more general solution you might want to include str.upper() as well, and to make it more general yet you might do a case-insensitive replacement with re.sub(x, y, text, flags=re.I) for anything that remains.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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