我怎样才能扩大一个词(s'cre​​am)中的撇号?

How can I expand the apostrophe in a word (s'cream)?

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

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)

您可以使用 regex 会更容易,用 .+ 替换撇号,这意味着

  • . 任意字符
  • + 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)

使用正则表达式很容易:

选择使用 \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
"""