![](/img/trans.png)
[英]Given a Dictionary and a list of letters, find all possible words that can be created with the letters
[英]Find the Words that Created by Removing Letters from Given String
我正在嘗試使用正則表達式和我的文本文件編寫代碼。 我的文件逐行包含這些詞:
each
expressions
flags
in
from
given
line
of
once
lines
no
我的目的是; 顯示通過從給定子字符串中刪除字母而創建的單詞。
例如; 如果我的子字符串是"flamingoes"
,我的輸出應該是;
flags
in
line
lines
no
因為它們是通過刪除字母從我的子字符串創建的,並且它們也在我的文本文件中。
我做了很多關於正則表達式的工作,但我對這個挑戰很感興趣。 是否有任何正則表達式解決方案?
您應該為要查找的每個單詞創建一個正則表達式。 表達式.*?
每個字母之間是一個非貪婪模式,這將避免回溯(至少其中一些),並使搜索更快。
例如,單詞“given”的正則表達式為g.*?i.*?v.*?e.*?n
import re
def hidden_words(needles, haystack):
for needle in needles:
regex = re.compile(('.*?').join(list(needle)))
if regex.search(haystack):
yield needle
needles = ['each', 'expressions', 'flags', 'in', 'from',
'given', 'line', 'of', 'once', 'lines', 'no']
print(*hidden_words(needles, 'flamingoes'), sep='\n')
基本上每個字符都是可選的。 一個簡單的
import re
word = 'flamingoes'
pattern = ''.join( c+'?' for c in word ) # ? Marks the letter as optional
for line in open('file').readLines():
line = line.strip()
m = re.match(pattern, line)
if m:
print(line)
應該夠了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.