例如,如果有句子“我有8支钢笔而我的朋友有7支笔” 我知道如何使用re.findall提取数字,结果将是['8','7']。但是,我想弄清楚句子中有多少组数字,答案是2。有人可以帮我做吗?谢谢
答案 0 :(得分:3)
只需使用findall()
输出的长度?
>>> sent = "I have 8 pens and my friend have 7 pens"
>>> import re
>>> re.findall(r'\d+', sent)
['8', '7']
>>> len(re.findall(r'\d+', sent))
2
或者,由于您要求提供一组数字,请将列表转换为一组(不包括任何双打)。
>>> sent = "I have 8 pens and my 8 friend have 7 pens"
>>> import re
>>> re.findall(r'\d+', sent)
['8', '8', '7']
>>> len(re.findall(r'\d+', sent))
3
>>> len(set(re.findall(r'\d+', sent)))
2
答案 1 :(得分:1)
要查找字符串中有多少个数字,您可以找到通过re.findall
调用创建的列表的长度。
In [1]: import re
In [2]: sentence = "I have 3 tacos, 2 burritos, and 3 tortas"
In [3]: re.findall(r'\d+', sentence)
Out[3]: ['3', '2', '3']
In [4]: len(re.findall(r'\d+', sentence))
Out[4]: 3
要查找字符串中存在多少个唯一数字,请将列表转换为集合并查找其长度。
In [5]: len(set(re.findall(r'\d+', sentence)))
Out[5]: 2
答案 2 :(得分:0)
你不能使用len(re.findall())
找到答案。
答案 3 :(得分:0)
如果您使用
amount = len(re.findall(sentence))
print(amount)
这应该工作。虽然,我必须承认我从未使用过re.findall,但它看起来像它创建了一个数字列表。因此,如果字符串位于名为sentence的变量中,则re.findall会生成一个数字列表。然后Len应该读取列表的长度。然后它将打印列表的长度。