首页 > 解决方案 > Python: Get unique numbers from a text

问题描述

Supposedly I have the following text:

text = "30 people work for 3 managers"

T I want to extract only 3 from the above text. The above text is just an example and can be arbitrary. The following code seems right but doesn't work

find = re.findall(r"3", text)

The output of this code is

 ['3', '3']
find = re.findall(r"(\d+)", text)

The above would also not work because i would get 30 and 3 both. I specifically want to 3.

The output also is in list. How do I convert to string. I do not want to use .join method or for loop. I would be eventually applying this code to a df. so I can use the .apply() method

标签: python-3.xpandasre

解决方案


如果我理解正确 - 你正在尝试所有出现的数字 3。你拉的原因

['3','3']

是因为您的文本中实际上有两个 '3'。30人一份也行。

您可以使用只是查找" 3 "而不是简单"3"地确保排除其他数字,如 30、33、13 等......


推荐阅读