pythonstringsearchmissing-symbols

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


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)

Solution

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

    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)