【问题标题】:selecting words that only have specific letters in them选择仅包含特定字母的单词
【发布时间】:2015-08-16 15:11:17
【问题描述】:

我试图只打印与我提供的正则表达式匹配的单词,并且只包含第二个参数中提供的字母。正则表达式可以完美运行,但字母选择却不行。

import re

def search(regex,letters):
    letters=set(letters)
    pattern=re.compile(regex)
    for word in content:
        word=word.strip()
        if(pattern.findall(word)):
            if letters & set(word):
                print(word)


#search(r'^(n|u|p|g|o|u|e|b|l){6}$')
#search(r'^t(i|a)[a-z]{3}')
content=["hello","helps","halts","random"]
search(r'^h(e|a)[a-z]{3}','hltsa') #returns: hello,helps,halts

我的目标是让它只返回暂停,因为它匹配第二个参数。

【问题讨论】:

  • if letters & set(word): 应该检查什么?
  • 我发现在这个stackoverflow.com/questions/9443302/… post中我认为它会检查一个单词是否包含这些字母
  • 尝试打印set(word),然后尝试打印letters,最后打印letters & set(word),看看它会给你什么;)

标签: regex python-2.7


【解决方案1】:
import re

def search(regex,letters):
    letters=set(letters)
    pattern=re.compile(regex)
    for word in content:
        word=word.strip()
        if(pattern.findall(word)):
            if set(word) >= letters:
                print(word)


#search(r'^(n|u|p|g|o|u|e|b|l){6}$')
#search(r'^t(i|a)[a-z]{3}')
content=["hello","helps","halts","random"]
search(r'^h(e|a)[a-z]{3}','hltsa') #returns: hello,helps,halts

试试这个,我只改了if letters & set(word):

在集合的文档中你可以找到这个

s.issubset(t)    s <= t  test whether every element in s is in t
s.issuperset(t)  s >= t  test whether every element in t is in s

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    相关资源
    最近更新 更多