![](/img/trans.png)
[英]Extract words/sentence that occurs before a keyword from a string - Python
[英]Removing words from a sentence before a keyword from a specific list
我有一個關鍵字列表keywords = [",", "or", "and"]
和一個句子s = built on the kernel, is written largely in
我想從上面列表中的任何關鍵字之前刪除上面句子中的所有單詞,在這種情況下是“,”。 所以 Output 將被is written largely in.
import re
keywords = [",", "or", "and"]
s = "built on the kernel, is written largely in"
split_sentence = re.split(',|or|and',s)[1:]
result = "".join(split_sentence)
print(result)
output:
is written largely in
您可以將re.split()
與模式一起使用為|
加入您的keywords
字符串。 它將返回由關鍵字分隔的字符串列表。 由於您需要list
的最后一個子字符串,您可以使用-1
作為索引來訪問它。
例如:
>>> import re
>>> keywords = [",", "or", "and"]
>>> my_str = "Hello, and, or, Stack Overflow"
>>> re.split('|'.join(keywords), my_str)[-1]
' Stack Overflow'
此外,如果您想從結果字符串中刪除額外的空格,那么您可以進一步在上述字符串上使用str.strip()
:
>>> re.split('|'.join(keywords), my_str)[-1].strip()
'Stack Overflow'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.