通過多次操作創建了兩個串列。
a = ["Cat", "Dog", "Pigeon", "Eagle", "Camel"]
b = ["Tiger", "Bat", "Whale", "Snake", "Bear"]
我正在嘗試使用此串列替換字串。(a) 使用一個串列來搜索一個詞和 (b) 用一個串列替換它。可以按照與每個串列相同的順序替換該順序。
每個單詞按串列順序替換為 cat -> Tiger / Dog -> Bat / Pigeon -> Whale / Eagle -> Snake /Camel -> Bear。
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.
.....
"""
期望的結果是
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.
.....
"""
除了這個,我還嘗試了很多其他的東西,但無濟于事。幫助
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
uj5u.com熱心網友回復:
嘗試回圈所有第二個串列并替換為第一個串列。
for i in range(len(a)):
if b[i] in text:
text = text.replace(b[i],a[i])
uj5u.com熱心網友回復:
str.replace在回圈中使用,并且由于a和b大寫,您需要對每個單詞的小寫版本執行單獨的替換操作:
>>> 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.
.....
以一種完全通用的方式來做這件事是很棘手的——例如,你會翻譯cAt成tIgeror tIGErortIgEr嗎?但是映射原始str.title()外殼以及str.lower()外殼對于這個特定的輸入是足夠的。對于更通用的解決方案,您可能還希望包括在內str.upper(),并使其更通用,但您可以對re.sub(x, y, text, flags=re.I)剩余的任何內容進行不區分大小寫的替換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488444.html
