查找以辅音开头和结尾的单词

2024-05-01 11:50:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出以辅音开头和结尾的单词。下面是我尝试过的,不是我要找的。我真的卡住了,需要你的帮助/建议。在

import re

a = "Still, the conflicting reports only further served to worsen tensions in the Ukraine crisis, which has grown drastically \
in the past few weeks to a new confrontation between Russia and the West reminiscent of low points in the Cold War." 

b = re.findall(" ([b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z, ',', '.'].+?[b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z, ',', '.']) ", a.lower())
print(b)

输出为:

^{pr2}$

但输出不正确。我必须使用正则表达式。如果没有它,我想那会太难了。在

非常感谢!在


Tags: thetoinimportreonly结尾单词
3条回答

这是一个使用^{}^{}的非常清晰的解决方案。为了实现您的目标,您必须自己去掉特殊的字符,并将字符串转换成单词列表(在代码中命名为s):

vowels = ('a', 'e', 'i', 'o', 'u')
[w for w in s if not w.lower().startswith(vowels) and not w.lower().endswith(vowels)]

首先,您应该split()a,这样就可以得到每个单词。然后检查第一个字母和最后一个字母是否在列表consonants中。如果是,您append将其all,并在最后打印all的内容。在

consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']

a = "Still, the conflicting reports only further served to worsen tensions in the Ukraine crisis, which has grown drastically \
in the past few weeks to a new confrontation between Russia and the West reminiscent of low points in the Cold War."

all = []

for word in a.split():
    if word[0] in consonants and word[len(word)-1] in consonants:
        all.append(word)

print all

试试这个:

vowels = ['a', 'e', 'i', 'o', 'u']
words = [w for w in a.split() if w[0] not in vowels and w[-1] not in vowels]

但是,这不会考虑以.,结尾的单词

编辑:如果必须使用regex查找模式:

^{pr2}$

然后我们需要找出所有不是以元音开头也不是以元音结尾的单词

ignore = [b for b in re.findall(begin_in_vowel, a) if b]
ignore.extend([b for b in re.findall(ending_in_vowel, a) if b])

结果是:

result = [word for word in a.split() if word not in ignore]

相关问题 更多 >