如何使用Python替換字串中的第K個單詞?


字串是Python中重要的資料型別。字串可以定義為字元序列。替換字串中的第k個單詞是一種操作,我們希望替換在字串中第k次出現的單詞。在本文中,我們將介紹幾種實現該操作的方法。我們將研究諸如使用迴圈語句、模組和庫(如re等)的暴力方法。

使用迴圈和split方法

迴圈在大多數現代程式語言中非常常見。我們可以使用for迴圈或while迴圈來迭代Python中的可迭代物件。另一方面,enumerate方法是Python中的內建方法,它返回一個列舉物件。該物件包含可迭代物件的索引和值對。要替換字串中的第k個單詞,我們可以遵循以下演算法

  • 首先將字串拆分為單詞。

  • 使用迴圈迭代可迭代物件。

  • 找到第k個單詞並將其替換為所需的單詞。

示例

在下面的程式碼中,我們使用了split方法將字串拆分為單詞。接下來,我們使用了Python的enumerate方法來迭代它,並且對於每次迭代,我們都繼續查詢該單詞是否是第k個單詞。如果它是序列中的第k個單詞,我們已將該單詞附加到我們稍後使用join方法將其轉換為字串資料型別的已初始化列表中。

def replace_kth_word(string, k, new_word):
    words = string.split()
    updated_words = []
    for i, word in enumerate(words):
        if i + 1 == k:
            updated_words.append(new_word)
        else:
            updated_words.append(word)
    updated_string = ' '.join(updated_words)
    return updated_string
test_string = "Apple is red"
k_value = 3
new_word_value = "sweet"
updated_string = replace_kth_word(test_string, k_value, new_word_value)
print("The original string is: " + test_string)
print("The updated string is: " + updated_string)

輸出

The original string is: Apple is red
The updated string is: Apple is sweet

使用Split方法和索引

split是Python的內建方法,它允許我們根據分隔符拆分Python字串。當我們嘗試從Python字串中檢索重要資訊時,它非常方便。

語法

string.split(delimiter)

這裡的“string”是我們想要對其執行split操作的字串物件的名稱。另一方面,分隔符是我們需要根據其拆分字串的序列。

示例

在下面的示例中,我們使用'split'方法將字串拆分為單詞。接下來,我們檢查k的值是否小於或等於列表的長度。如果是True,那麼我們已經用我們想要的單詞替換了該索引處的單詞。

def replace_kth_word(string, k, new_word):
    words = string.split()
    if k <= len(words):
        words[k - 1] = new_word
    return ' '.join(words)
sentence = "Hello I will replace dog with cat"
k = 7
new_word = "lion"
updated_sentence = replace_kth_word(sentence, k, new_word)
print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

輸出

The original String is: Hello I will replace dog with cat
The updated String is: Hello I will replace dog with lion

使用正則表示式

正則表示式最初是為處理NLP問題而設計的。正則表示式是查詢字串中重要模式和特徵的方法。它使用萬用字元模式來確定特徵。在Python中,我們有一個單獨的庫叫做're'。該庫在機器學習、文字解析、文字預處理等各種領域都很有用。

示例

在下面的示例中,我們使用了're'庫。我們在'pattern'變數中定義了模式。接下來,我們使用're'庫的'findall'方法在給定的字串中查詢模式。接下來,我們使用lambda函式彈出第k個索引處的元素並將其替換為我們想要的字串。

import re

def replace_kth_word_regex(string, k, new_word):
    pattern = r'\b(\w+)\b'
    words = re.findall(pattern, string)
    if k < len(words):
        words[k - 1] = new_word
    return re.sub(pattern, lambda m: words.pop(0), string)
sentence = "Apple is my favourite fruit"
k = 1
new_word = "Orange"
updated_sentence = replace_kth_word_regex(sentence, k, new_word)
print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

輸出

The original String is: Apple is my favourite fruit
The updated String is: Orange is my favourite fruit

使用列表推導式

列表推導式是一種簡潔且優雅的方式,可以將多個表示式、語句等組合到單個表示式中以生成列表的元素。使用此方法的優點是我們可以將多個語句組合在一行中,並且可以利用其他方法,例如lambda和map函式。

示例

在下面的示例中,我們首先使用'split'方法將字串拆分為單詞列表。接下來,我們使用了列表推導式,在其中我們檢查列表中單詞的索引是否等於k,如果是,我們已將其替換為所需的單詞。最後,我們使用了'join'方法來從列表中建立字串。

def replace_kth_word_generator(string, k, new_word):
    words = string.split()
    updated_words = [new_word if i == k else word for i, word in enumerate(words)]
    return ' '.join(updated_words)

sentence = "He has a house in London"
k = 3
new_word = "flat"
updated_sentence = replace_kth_word_generator(sentence, k, new_word)
print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

輸出

The original String is: He has a house in London
The updated String is: He has a flat in London

僅使用Join和索引方法

‘join’是Python中的內建方法,我們可以用它來組合多個字串。它將任何可迭代物件作為引數,並將可迭代物件的元素連線起來。另一方面,索引是訪問可迭代物件中元素位置的常用方法。它被定義為任何元素與可迭代物件中第一個元素的距離。

示例

在下面的示例中,我們使用了join方法和索引來替換第k個單詞。我們首先使用Python的split方法將字串拆分為列表。接下來,我們使用jon方法將元素追加到第k個索引,新單詞和第k個元素之後的元素到空字串中。

def replace_kth_word_regex_sub(string, k, new_word):
    temp = string.split(' ')
    updated_sentence = " ".join(temp[: k]  + [new_word] + temp[k + 1 :])
    return updated_sentence

sentence = "He has a house in London"
k = 3
new_word = "flat"
updated_sentence = replace_kth_word_regex_sub(sentence, k, new_word)

print(f"The original String is: {sentence}")
print(f"The updated String is: {updated_sentence}")

輸出

The original String is: He has a house in London
The updated String is: He has a flat in London

結論

在本文中,我們瞭解瞭如何使用Python替換字串中的第k個單詞。我們可以採用暴力方法,例如使用迴圈語句、split等。我們可以直接使用split方法和索引屬性訪問單詞。像're'這樣的庫允許我們採用不同的方法來執行相同的操作,在該方法中,我們透過正則表示式而不是索引來替換它。

更新於:2023年7月18日

141 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告