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

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

如何擴展單詞中的撇號(s'cre??am)?

如何擴展單詞中的撇號(s'cre??am)?

明月笑刀無情 2023-07-05 10:21:42
這是我的單詞表。(實際上我正在使用一個大列表。)bananafishscreamscreamingsuncreamsuncreams我想擴大s'cream。它必須suncream僅匹配。不匹配,scream因為沒有撇號字符。不匹配,suncreams因為末尾的 s 下落不明。我對它的編程不是很好,因為它只匹配所有的單詞。我嘗試過的。這很尷尬。我不知道我在做什么。find = "s'cream"with open('words') as f:    for line in f:        word = line.strip()        skipchars = False        for c in find:            if c == "'":                skipchars = True                continue            if skipchars:                for w in word:                    if c != w:                        continue            if c not in word:                break            skipchars = False        print(word)
查看完整描述

2 回答

?
慕無忌1623718

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

你可以用regex那個會更容易,用.+which的意思替換撇號

  • . 任何字符

  • + 1次或多次

import re


words = ['banana', 'fish', 'scream', 'screaming', 'suncream', 'suncreams']


find = "s'cream"

pattern = re.compile(find.replace("'", ".+"))


for word in words:

    if pattern.fullmatch(word):

        print(word)


查看完整回答
反對 回復 2023-07-05
?
HUH函數

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

使用正則表達式這很容易:


使用的選擇\w+是與“單詞”字符(如字母)匹配,并且要求至少有 1 個與其映射的字符。


import re


find = "s'cream"


words = [

"banana",

"fish",

"scream",

"screaming",

"suncream",

"suncreams"

]


target_re = re.compile("^{}$".format(find.replace("'", "\w+")))

for word in words:

    if target_re.match(word):

        print("Matched:", word)

    else:

        print("Not a match:", word)


"""

output:

Not a match: banana

Not a match: fish

Not a match: scream

Not a match: screaming

Matched: suncream

Not a match: suncreams

"""


查看完整回答
反對 回復 2023-07-05
  • 2 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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