1

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

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)
4

2 回答 2

2

您可能会使用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)
于 2020-08-31T06:04:47.993 回答
1

使用正则表达式很容易:

使用的选择\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
"""
于 2020-08-31T06:04:53.910 回答