[英]How do I remove a substring with repeating pattern in Python?
所以,我有以下列表:
texts = ["Vol. 1, No. 2, 2020 other text yes bla bla",
"Vol. 2, No. 2, 2020 another text",
"Vol. 1, No. 1, 2020 yet another one"]
看,我想獲取另一個文本,其他文本等,並刪除“Vol. x No. x, 2020”substring。 我該如何使用正則表達式? 我認為使用{}
可以幫助我刪除它,但似乎我並不真正了解它是如何工作的。
def remove_header_footer(text):
pattern1 = "Vol. {}, No. {}, 2020"
temp = text.replace(pattern1, text, "")
我得到了一個錯誤。 有人有什么主意嗎? 謝謝你。
你可以試試這個模式'Vol. \d, No. \d, 2020'
'Vol. \d, No. \d, 2020'
鑒於 Vol. 之后的字符串。 No. 是個位數。 對於多個數字,您可以使用 \d+
import re
texts = ["Vol. 1, No. 2, 2020 other text yes bla bla",
"Vol. 2, No. 2, 2020 another text",
"Vol. 1, No. 1, 2020 yet another one"]
for text in texts:
new_text = re.sub('Vol. \d, No. \d, 2020', '', texts[0])
print(new_text)
如果 alignment 始終相同,您可以嘗試以下簡單方法:
result = []
for text in texts:
text_split = text.split(" ")
result.append(text_split[5:])
這將在每個“;”處分開在您的列表中,然后在每個blank
拆分。 稍后,當附加到結果列表時,前 5 個條目將被省略。 如果您願意,您可以將列表展平:
flat_result = [item for sublist in result for item in sublist]
如果文本總是以這種方式格式化,您可能會在2020
將它們.split
一次並帶上最后一部分,即
texts = ["Vol. 1, No. 2, 2020 other text yes bla bla",
"Vol. 2, No. 2, 2020 another text",
"Vol. 1, No. 1, 2020 yet another one"]
for t in texts:
print(t.split(" 2020 ", 1)[-1])
output
other text yes bla bla
another text
yet another one
請注意,我在 2020 空間而不是 2020 空間進行拆分並執行一次( .split
中的第二個參數為 1),因此如果 2020 出現在進一步的測試中沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.