繁体   English   中英

在 Python 中使用正则表达式查找具有某些字符和不包含其他字符的单词

[英]Using Regex in Python to find words with certain characters and without other characters

首先,我是正则表达式的新手,我正在使用https://regex101.com/r/arkkVE/3来帮助我学习它。

我想从我使用 re 的 a.txt 文件中查找单词。 到目前为止,我能够做到这一点,但它非常冗长,我正试图减少正则表达式的重复序列。

目前这就是我所拥有的

Possibility = list()
with open('5LetterWords.txt') as f:
    for line in f.readlines():
        Possibility += re.findall(r'(?=\w)(?=.*[@#t])[\w]+(?=\w)(?=.*[@#o])[\w]+(?=\w)(?=.*[@#u])[\w]+'
        , line)
    print(Possibility)

这会找到没有特定顺序的字母“t”、“o”和“u”的单词,这是我想要的第一步。

我想添加其他正则表达式,这些表达式将省略具有其他字符的单词,但我不知道如何使用正则表达式进行排除。

正如你所看到的,这开始变得非常长而且丑陋。

我应该使用正则表达式吗? 有没有更好/更简洁的方法来解决这个问题?

谢谢

理想情况下,您将逐行读取文件并检查每个单词是否存在tou并另外检查a是否存在。

我不是 Python 开发人员,但这似乎相关: https://stackoverflow.com/a/5189069/2191572

if ('t' in word) and ('o' in word) and ('u' in word) and ('a' not in word):
    print('yay')
else:
    print('nay')

如果您坚持使用正则表达式,那么这将起作用:

^(?=.*t)(?=.*o)(?=.*u)(?!.*a).*$
  • ^ - 起始线锚点
  • (?=.*t) - 在我前面有一个t
  • (?=.*o) - 在我前面有一个o
  • (?=.*u) - 在我面前有一个u
  • (?..*a) - 在我前面没有a s
  • .* - 捕捉一切
  • $ - 结束线锚

注意: (?..*a).*可以替换为[^a]*

https://regex101.com/r/WtVr8S/1

我想您可以遍历您的单词列表并过滤掉您想要或不想要的单词,例如

words = ['about', 'alout', 'aotus', 'apout', 'artou', 'atour', 'blout', 'bottu', 'bouet', 'boult', 'bouto', 'bouts', 'chout', 'clout', 'count', 'court', 'couth', 'crout', 'donut', 'doubt', 'flout', 'fotui', 'fount', 'foute', 'fouth', 'fouty', 'glout', 'gouty', 'gouts', 'grout', 'hoult', 'yourt', 'youth', 'joust', 'keout', 'knout', 'lotus', 'louty', 'louts', 'montu', 'moult', 'mount', 'mouth', 'nobut', 'notum', 'notus', 'plout', 'pluto', 'potus', 'poult', 'pouty', 'pouts', 'roust', 'route', 'routh', 'routs', 'scout', 'shout', 'skout', 'smout', 'snout', 'south', 'spout', 'stoun', 'stoup', 'stour', 'stout', 'tatou', 'taupo', 'thous', 'throu', 'thuoc', 'todus', 'tofus', 'togue', 'tolus', 'tonus', 'topau', 'toque', 'torus', 'totum', 'touch', 'tough', 'tould', 'tourn', 'tours', 'tourt', 'touse', 'tousy', 'toust', 'touts', 'troue', 'trout', 'trouv', 'tsubo', 'voust']
result = []
for word in words:
    if ('a' in word) or ('y' in word):
        continue    #to skip
    elif ('t' in word) or ('u' in word) or ('o' in word):
        result.append(word)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM