簡體   English   中英

刪除撇號后的字符串內容

[英]Remove string contents after apostrophe

我正在嘗試從句子中刪除撇號標點符號'之后的字符串內容。

例如,給出一句話This is the world's first engine. You'll learn more about this later. This is the world's first engine. You'll learn more about this later.

預期的輸出是This is the world first engine. You learn more about this later. This is the world first engine. You learn more about this later.

我可以使用re.sub()刪除撇號 ' 。 但是,我無法刪除撇號后的內容

re.sub(r'[^\\w]', ' ', value)

我也使用過 python replace() 但是,這不是通用的解決方案

value.replace("'s", "")

任何幫助表示贊賞。 謝謝你!

要刪除str中的撇號和尾隨字母,您可以使用以下代碼。

import re

s = "This is the world's first engine. You'll learn more about this later."
s = re.sub(r'\'\w+', '', s)
print(s)

輸出This is the world first engine. You learn more about this later. This is the world first engine. You learn more about this later.

模式\\'\\w+匹配后跟一個或多個單詞字符的撇號, re.sub()用於用空字符串 ( '' ) 替換此模式的任何匹配項。

您可以使用re.sub()如下

import re
def clean(value):
    return re.sub(r'\'\w{,2}', '', value)

print(clean("This is the world's first engine. You'll learn more about this later"))

試試這個(我想正則表達式有更簡單的解決方案):

s="This is the world's first engine. You'll learn more about this later."

s=' '.join(list(map(lambda x: x[:x.find("'")] if "'" in x else x, s.split(' '))))

>>> print(s)
'This is the world first engine. You learn more about this later.'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM