我想去掉一串标点符号,结果用了
re.findall(r"[\w]+|[^\s\w]", text)
它工作得很好,确实解决了我的问题。我不明白的是括号内的细节和整个模式。r"[\w]+|[^\s\w]"
到底是什么意思?我在python标准库中找到它,它说:
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.
我不确定我是否明白这一点,而且澄清听起来有点模糊。有谁能告诉我这个上下文中的模式是什么意思,它是如何在findall()方法中定义的?在
\w
表示字母数字字符加上“u”。并且\s
表示空格字符,包括“\t\r\n\v\f”和空格字符“”。所以,[\w]+|[^\s\w]
意味着一个只包含单词和“uu”的字符串。在为了分解它,}。相反,您也可能会看到}的内容。最后,您还将看到字符范围:
[]
创建一个character class。您经常会看到类似[abc]
的内容,它将匹配a
、b
或{[^abc]
将匹配任何不是a
、b
或{[a-cA-C]
。这引入了两个范围,它将匹配a
、b
、c
、A
、B
、C
中的任何一个。在在本例中,character类包含特殊标记。}。}范围内的任何内容。
\w
和{\w
匹配任何类似的字母。\w
实际上取决于您的语言环境,但它通常与[a-zA-Z0-9_]
匹配a-z
、A-Z
、0-9
或{\s
类似,但它匹配任何可以被视为空白的内容。在+
表示您可以重复前面的匹配1次或更多次。因此[a]+
将匹配整个字符串aaaaaaaaaaa
。在您的例子中,您匹配的是相邻的字母数字字符。在|
基本上类似于“或”。匹配左侧的内容,或如果左侧的内容不匹配,则匹配右侧的内容。在相关问题 更多 >
编程相关推荐