我有一個串列,我想洗掉所有第一篇文章:[“房子”、“美麗的花園”、“房子的美麗花園”]
我希望串列只包含:[“房子”、“美麗的花園”、“房子的美麗花園”]
如果第一個詞是文章,則洗掉。如果文章出現在句子中,則應保留。
uj5u.com熱心網友回復:
如果您正在使用 python 嘗試
new_list = [s[4:] if s.startswith('the ') else s for s in old_list]
uj5u.com熱心網友回復:
另一種選擇是使用re(此示例還將忽略第一個周圍的空格the:
import re
lst = ["the house", "the beautiful garten", "the beautiful garten of the house"]
pat = re.compile(r"^\s*the\s ", flags=re.I)
out = [pat.sub("", w) for w in lst]
print(out)
印刷:
['house', 'beautiful garten', 'beautiful garten of the house']
uj5u.com熱心網友回復:
如果您有要修剪的潛在文章或單詞串列,您可以執行以下操作以洗掉該單詞以及以下空格:
articles = ["the", "a", "an"]
sentences = ["the house", "a beautiful garten", "an amazing garten of the house"]
out = []
for s in sentences:
new = s
for a in articles:
if s.startswith(f'{a} '):
new = s[len(a) 1:]
out.append(new)
print(out)
['house', 'beautiful garten', 'amazing garten of the house']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527077.html
標籤:Python列表文章
上一篇:如何比較PySpark資料框中的列對和更改的記錄數?
下一篇:如何在python中分隔文本行
