python 如何查找以特定字符开头的单词

kpbpu008  于 2023-01-16  发布在  Python
关注(0)|答案(6)|浏览(187)

我想用python把句子中以"s"开头的单词整理出来。
下面是我的代码:

import re
text = "I was searching my source to make a big desk yesterday."
m = re.findall(r'[s]\w+', text)
print m

但代码的结果是:

['searching', 'source', 'sk', 'sterday'].

我怎样写一段关于正则表达式的代码?或者,有没有什么方法来整理单词?

lsmepo6l

lsmepo6l1#

>>> import re
>>> text = "I was searching my source to make a big desk yesterday."
>>> re.findall(r'\bs\w+', text)
['searching', 'source']

对于小写和大写s,用途:r'\b[sS]\w+'

o75abkj4

o75abkj42#

我知道这不是正则表达式解决方案,但您可以使用startswith

>>> text="I was searching my source to make a big desk yesterday."
>>> [ t for t in text.split() if t.startswith('s') ]
['searching', 'source']
qyzbxkaa

qyzbxkaa3#

1.如果要匹配单个字符,则不需要将其放在字符类中,因此s[s]相同。
1.您要查找的是word boundary。单词边界\b是一个锚点,它匹配从非单词字符(\W)到单词字符(\w)的更改,反之亦然。
解决办法是:

\bs\w+

此正则表达式将匹配之前没有单词字符的s(也适用于字符串的开头),并且在它之后需要至少一个单词字符。\w+匹配它可以找到的所有单词字符,因此在结尾不需要\b
看它here on Regexr

2jcobegt

2jcobegt4#

    • Lambda样式:**
text = 'I was searching my source to make a big desk yesterday.'

list(filter(lambda word: word[0]=='s', text.split()))
    • 输出:**

['searching', 'source']

wribegjk

wribegjk5#

我试过这个代码样本,我认为它完全符合您的要求:

import re
text = "I was searching my source to make a big desk yesterday."
m = re.findall (r'\b[s]\w+', text)
print (m)
0x6upsns

0x6upsns6#

我想在这里补充一点,
假设您有一行要查找以's'开头的单词

line = "someone should show something to some@gmail.com"

如果编写正则表达式,

swords = re.findall(r"\b[sS]\w+", line)

输出将是,

['someone','should','show','something','some']

但如果将正则表达式修改为,

# use \S instead of \w
swords = re.findall(r"\b[sS]\S+", line)

输出将是,

['someone','should','show','something','some@gmail.com']

相关问题