Python正则表达式将字符串转换为单词列表(包括带连字符的单词)

3 投票
5 回答
4658 浏览
提问于 2025-04-16 02:18

我想从一个字符串中提取出所有的单词,包括带连字符的单词。现在的代码是:

s = '-this is. A - sentence;one-word'
re.compile("\W+",re.UNICODE).split(s)

这个代码返回的是:

['', 'this', 'is', 'A', 'sentence', 'one', 'word']

而我希望它能返回:

['', 'this', 'is', 'A', 'sentence', 'one-word']

5 个回答

1

这段代码的意思是,我们有一个字符串s,里面有一些单词和符号。我们想要从这个字符串中找出所有的单词。

代码中的`re.findall`是一个用来查找字符串中符合特定规则的内容的函数。在这里,它的规则是:首先找带有连字符(-)的单词,比如“one-word”,如果没有找到,就找普通的单词,包括字母和撇号(')的组合。

运行这段代码后,得到的结果是一个列表,里面包含了所有找到的单词,结果是:['this', 'is', 'A', 'sentence', 'one-word', "what's"]。

注意,代码的顺序是先找带连字符的单词,这一点很重要!

2

这里是我传统的“为什么要使用正则表达式语言,而不是直接用Python”的替代方案:

import string
s = "-this is. A - sentence;one-word what's"
s = filter(None,[word.strip(string.punctuation)
                 for word in s.replace(';','; ').split()
                 ])
print s
""" Output:
['this', 'is', 'A', 'sentence', 'one-word', "what's"]
"""
4

如果你不需要开头的空字符串,可以使用这个模式 \w(?:[-\w]*\w)? 来进行匹配

>>> import re
>>> s = '-this is. A - sentence;one-word'
>>> rx = re.compile(r'\w(?:[-\w]*\w)?')
>>> rx.findall(s)
['this', 'is', 'A', 'sentence', 'one-word']

需要注意的是,这个模式无法匹配带有撇号的单词,比如 won't

撰写回答