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

53 Views Asked by At

Here is my word list. (In reality I am using a big list.)

banana
fish
scream
screaming
suncream
suncreams

I want to expand s'cream. It must match suncream only.

Not match scream because there are no characters for the apostrophe.

Not match suncreams because the s at the end is unaccounted for.

I am not programming it very well because it just matches all the words.

What I tried. It is embarrassing. I don't know what I'm doing.

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

There are 2 best solutions below

2
azro On BEST ANSWER

You may use regex that would be more easier, replace the apostrophe by .+ which means

  • . anychar
  • + 1 or more times
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)
0
M Z On

This is easy with regex:

The choice to use \w+ is to match with "word" characters (like letters) and a requirement of at least 1 character it maps with.

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
"""