猿问

如何扩展单词中的撇号(s'cre​​am)?

这是我的单词表。(实际上我正在使用一个大列表。)


banana

fish

scream

screaming

suncream

suncreams

我想扩大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)


明月笑刀无情
浏览 114回答 2
2回答

慕无忌1623718

你可以用regex那个会更容易,用.+which的意思替换撇号. 任何字符+ 1次或多次import rewords = ['banana', 'fish', 'scream', 'screaming', 'suncream', 'suncreams']find = "s'cream"pattern = re.compile(find.replace("'", ".+"))for word in words:    if pattern.fullmatch(word):        print(word)

HUH函数

使用正则表达式这很容易:使用的选择\w+是与“单词”字符(如字母)匹配,并且要求至少有 1 个与其映射的字符。import refind = "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: bananaNot a match: fishNot a match: screamNot a match: screamingMatched: suncreamNot a match: suncreams"""
随时随地看视频慕课网APP

相关分类

Python
我要回答