亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在python中按特定順序查找子字符串

在python中按特定順序查找子字符串

幕布斯6054654 2021-09-23 09:27:44
我有一長串字符串,其中包含按給定順序排列的感興趣的子字符串,但這里有一個在文本文件中使用句子的小例子:This is a long drawn out sentence needed to emphasize a topic I am trying to learn.It is new idea for me and I need your help with it please!Thank you so much in advance, I really appreciate it.從這個文本文件,我想找到同時包含任何句子"I"和"need",但他們必須在出現的順序。因此,在這個例子中,'I'并且'need'都發生在第1句和第2句,但句子1他們是在錯誤的順序,所以我不想返回。我只想'I need'按順序返回第二句話。我用這個例子來識別子字符串,但我不知道如何只按順序找到它們:id1 = "I"id2 = "need"with open('fun.txt') as f:    for line in f:        if id1 and id2 in line:            print(line[:-1])這將返回:This is a long drawn out sentence needed to emphasize a topic I am trying to learn.It is new idea for me and I need your help with it please!但我只想:It is new idea for me and I need your help with it please!謝謝!
查看完整描述

3 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

您可以使用正則表達式來檢查這一點。一種可能的解決方案是:


id1 = "I"

id2 = "need"

regex = re.compile(r'^.*{}.*{}.*$'.format(id1, id2))


with open('fun.txt') as f:

    for line in f:

        if re.search(regex, line):

            print(line[:-1])


查看完整回答
反對 回復 2021-09-23
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

您需要確定id2在該行的部分后 id1:


infile = [

    "This is a long drawn out sentence needed to emphasize a topic I am trying to learn.",

    "It is new idea for me and I need your help with it please!",

    "Thank you so much in advance, I really appreciate it.",

]


id1 = "I"

id2 = "need"


for line in infile:

    if id1 in line:

        pos1 = line.index(id1)

        if id2 in line[pos1+len(id1) :] :

            print(line)

輸出:


It is new idea for me and I need your help with it please!


查看完整回答
反對 回復 2021-09-23
  • 3 回答
  • 0 關注
  • 284 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號