gpt4 book ai didi

Python 正则表达式字符串到单词列表(包括带连字符的单词)

转载 作者:太空宇宙 更新时间:2023-11-03 13:05:42 27 4
gpt4 key购买 nike

我想解析一个字符串以获得一个包含所有单词(也包括带连字符的单词)的列表。当前代码是:

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']

最佳答案

如果不需要前导空字符串,可以使用模式 \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

关于Python 正则表达式字符串到单词列表(包括带连字符的单词),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3406771/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com