gpt4 book ai didi

python 正则表达式 : how to split string into distinct groups based on alphabets, 数字和标点符号

转载 作者:行者123 更新时间:2023-11-30 23:44:08 25 4
gpt4 key购买 nike

我正在使用 python 2.7 学习正则表达式

给定一个句子(假设小写和ascii),例如:

input = 'i like: a, b, 007 and c!!'

我如何将输入字符串标记为

['i', 'like', ':', 'a', ',', 'b', ',', '007', 'and', 'c', '!!']

我可以用 C++ 编写自动机并编写转换矩阵,但我想用 python 来实现

我无法想出一个正则表达式来一次性匹配这些不同类别的字母、数字和标点符号。

我看过几个 stackoverflow 帖子 herehere ,但并不完全遵循他们的方法。

我已经尝试了一段时间,非常感谢您的帮助。

PS:这不是家庭作业问题

最佳答案

>>> from string import punctuation
>>> text = 'i like: a, b, 007 and c!!'
>>> re.findall('\w+|[{0}]+'.format(punctuation),text)
['i', 'like', ':', 'a', ',', 'b', ',', '007', 'and', 'c', '!!']

这也有效,但如果找不到字母数字字符,则会找到任何非空白字符

>>> re.findall('\w+|\S+',text)
['i', 'like', ':', 'a', ',', 'b', ',', '007', 'and', 'c', '!!']

关于python 正则表达式 : how to split string into distinct groups based on alphabets, 数字和标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10260289/

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