python3提取字符串中的数字_如何在Python中从字符串中提取数字?
14 回复 | 直到 1 年前
1
430
3 年前
如果只想提取正整数,请尝试以下操作:
>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
我认为这比regex示例好有三个原因。首先,您不需要另一个模块;其次,它更可读,因为您不需要解析regex mini语言;第三,它更快(因此可能更像是pythonic):
python -m timeit -s "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "[s for s in str.split() if s.isdigit()]"
100 loops, best of 3: 2.84 msec per loop
python -m timeit -s "import re" "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "re.findall('\\b\\d+\\b', str)"
100 loops, best of 3: 5.66 msec per loop
这将无法识别浮点数、负整数或十六进制格式的整数。如果你不能接受这些限制,
slim's answer below
会成功的。
2
404
4 年前
我会用regexp:
>>> import re
>>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
['42', '32', '30']
这也将匹配来自
bla42bla
. 如果只希望数字由单词边界(空格、句点、逗号)分隔,则可以使用\b:
>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')
['42', '32', '30']
以数字列表而不是字符串列表结束:
>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
[42, 32, 30]
3
81
2 年前
这已经有点晚了,但是您也可以扩展regex表达式来解释科学符号。
import re
# Format is [(, ), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
('hello X42 I\'m a Y-32.35 string Z30',
['42', '-32.35', '30']),
('he33llo 42 I\'m a 32 string -30',
['33', '42', '32', '-30']),
('h3110 23 cat 444.4 rabbit 11 2 dog',
['3110', '23', '444.4', '11', '2']),
('hello 12 hi 89',
['12', '89']),
('4',
['4']),
('I like 74,600 commas not,500',
['74,600', '500']),
('I like bad math 1+2=.001',
['1', '+2', '.001'])]
for s, r in ss:
rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
if rr == r:
print('GOOD')
else:
print('WRONG', rr, 'should be', r)
一切都好!
4
67
10 年前
我假设你想要的不是整数,而是浮点数,所以我会这样做:
l = []
for t in s.split():
try:
l.append(float(t))
except ValueError:
pass
请注意,此处发布的其他一些解决方案不适用于负数:
>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string -30')
['42', '32', '30']
>>> '-3'.isdigit()
False
5
57
1 年前
如果你知道它只会是字符串中的一个数字,即“Hello12Hi”,你可以尝试过滤。
例如:
In [1]: int(''.join(filter(str.isdigit, '200 grams')))
Out[1]: 200
In [2]: int(''.join(filter(str.isdigit, 'Counters: 55')))
Out[2]: 55
In [3]: int(''.join(filter(str.isdigit, 'more than 23 times')))
Out[3]: 23
但要小心!!! :
In [4]: int(''.join(filter(str.isdigit, '200 grams 5')))
Out[4]: 2005
6
12
2 年前
# extract numbers from garbage string:
s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
listOfNumbers = [float(i) for i in newstr.split()]
print(listOfNumbers)
[12.0, 3.14, 0.0, 1.6e-19, 334.0]
7
12
2 年前
我正在寻找一个解决方案,以删除字符串的面具,特别是从巴西电话号码,这篇文章没有回答,但启发了我。这是我的解决方案:
>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'
8
7
4 年前
这个答案还包含当数字在字符串中浮动时的情况
def get_first_nbr_from_str(input_str):
'''
:param input_str: strings that contains digit and words
:return: the number extracted from the input_str
demo:
'ab324.23.123xyz': 324.23
'.5abc44': 0.5
'''
if not input_str and not isinstance(input_str, str):
return 0
out_number = ''
for ele in input_str:
if (ele == '.' and '.' not in out_number) or ele.isdigit():
out_number += ele
elif out_number:
break
return float(out_number)
9
6
1 年前
使用下面的Regex
lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
match = re.search(repl_str, word)
if match:
output.append(float(match.group()))
print (output)
与芬德尔
re.findall(r'\d+', "hello 12 hi 89")
['12', '89']
re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")
['12', '89', '777']
10
5
2 年前
我惊奇地发现,还没有人提到
itertools.groupby
作为实现这一目标的另一种选择。
from itertools import groupby
my_str = "hello 12 hi 89"
l = [int(''.join(i)) for is_digit, i in groupby(my_str, str.isdigit) if is_digit]
持有的价值
l
将:
[12, 89]
附言:
这只是为了说明我们也可以使用
groupby
为了达到这个目的。但这不是一个推荐的解决方案。如果你想做到这一点,你应该使用
accepted answer of fmark
基于使用列表理解
str.isdigit
作为过滤器。
11
2
3 年前
因为这些都不是我需要找到的excel和word文档中的真实财务数字,这里是我的变体。它处理整数、浮点数、负数、货币数(因为它在拆分时不应答),并且可以选择删除小数部分,只返回整数,或者返回所有内容。
它还处理印度Laks数字系统,其中逗号出现不规则,而不是每3个数字分开。
它不处理科学记数法或预算中括号内的负数——将显示为正数。
它也不提取日期。有更好的方法可以在字符串中找到日期。
import re
def find_numbers(string, ints=True):
numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
numbers = numexp.findall(string)
numbers = [x.replace(',','') for x in numbers]
if ints is True:
return [int(x.replace(',','').split('.')[0]) for x in numbers]
else:
return numbers
12
2
1 年前
我只是添加这个答案,因为没有人使用异常处理添加了一个,而且这也适用于float
a = []
line = "abcd 1234 efgh 56.78 ij"
for word in line.split():
try:
a.append(float(word))
except ValueError:
pass
print(a)
输出:
[1234.0, 56.78]
13
1
6 年前
@吉玛纳斯,我喜欢你的回答,但没有找到花车。我正在编写一个脚本来解析去CNC工厂的代码,需要同时找到X和Y维度,它们可以是整数或浮点数,所以我将您的代码修改为以下内容。这将找到int,浮点值为正和负。仍然找不到十六进制格式的值,但是可以将“x”和“A”到“F”添加到
num_char
tuple和我认为它可以解析像“0x23AC”这样的东西。
s = 'hello X42 I\'m a Y-32.35 string Z30'
xy = ("X", "Y")
num_char = (".", "+", "-")
l = []
tokens = s.split()
for token in tokens:
if token.startswith(xy):
num = ""
for char in token:
# print(char)
if char.isdigit() or (char in num_char):
num = num + char
try:
l.append(float(num))
except ValueError:
pass
print(l)
14
0
2 年前
我找到的最佳选择如下。它将提取一个数字,并可以消除任何类型的字符。
def extract_nbr(input_str):
if input_str is None or input_str == '':
return 0
out_number = ''
for ele in input_str:
if ele.isdigit():
out_number += ele
return float(out_number)
15
0
1 年前
line2 = "hello 12 hi 89"
temp1 = re.findall(r'\d+', line2) # through regular expression
res2 = list(map(int, temp1))
print(res2)
你好,
可以使用findall表达式通过数字搜索字符串中的所有整数。
在第二步中,创建一个列表res2,并将字符串中的数字添加到此列表中
希望这有帮助
当做,
迪瓦卡·夏尔马
python3提取字符串中的数字_如何在Python中从字符串中提取数字?相关推荐
- python怎么判断输入的是不是数字_如何在PYTHON里判断字符串是否为数字
1 打开JUPYTER NOTEBOOK,新建一个空白的PY文档. 2 str1 = "888" print(str1.isdecimal()) print(str1.isdigi ...
- python3读取excel某一列_怎样用python,读取excel中的一列数据!python读取excel某一列数据...
Python 如何循环读取csv或者excel中的一列数据,写入到中搜索 是可以 a.csv复制到 b.csv中 import csv def foo(): with open('a.csv', 'r ...
- python右对齐 数字_如何在Python中右对齐数值数据?
我有一些数据,我显示在3列格式,形式"键:值键:键:值键:值".这里有一个例子: p: 1 sl: 10 afy: 4 q: 12 lg: 10 kla: 3 r: 0 kl: 1 ...
- python中如何追加_如何在Python中将元素添加到列表中-追加,扩展和插入
在Python中使用列表时,您通常会希望向列表中添加新元素. Python列表数据类型具有三种添加元素的方法:append()-将单个元素追加到列表. extend() -将iterable的元素添加 ...
- python中第三方模块_如何在python脚本中包含第三方模块?
我已经开始使用Python来自动化我工作中的重复任务,并且经常需要将对第三方模块的引用集成到我的脚本中.如何将这些文件直接包含在脚本中?我知道有一些方法可以在python安装文件夹(C:\Python ...
- python移动文件中某个内容_如何在Python中移动文件
如何在Python中移动文件 我查看了Python $ mv ...接口,但无法找到移动文件的方法. 我如何在Python中执行相当于$ mv ...的操作? >>> source_ ...
- python中获取文件大小_如何在Python中获取文件大小
python中获取文件大小 We can get file size in Python using the os module. 我们可以使用os模块在Python中获取文件大小. Python中的 ...
- python字符串为什么不能修改_为什么在Python(\n)中更改字符串中的行不起作用?...
在大多数情况下,它可以完成任务,但有时(我很难精确地说,它依赖于什么)它会陷入一个无限循环中,因为它不切分文本字符串.在def insertNewlines(text, lineLength): &q ...
- python列表中随机选择_如何在Python中从列表中随机选择一个项目?
python列表中随机选择 Python random module provides an inbuilt method choice() has an ability to select a ra ...
最新文章
- java.security.InvalidKeyException: Illegal key size or default parameters
- 锁定文件失败 打不开磁盘“D:\vms\S1\CentOS 64 位.vmdk”或它所依赖的某个快照磁盘(强制关机后引起的问题)...
- 你当真了解count(*)count(id)count(1)吗?
- 前端常用linux命令
- linux系统怎样写单片机程序,单片机知识是Linux驱动开发的基础之一以及如何学单片机...
- 软件史上最伟大的十大程序员
- android调用文件管理器回调,Android中调用系统管理器选择文件并返回绝对路径
- pivottablejs|在Jupyter 中尽情使用数据透视表!
- oracle 相关1
- Hyperledger Fabric 或 Composer 获取指定区块的信息
- 小客车年检(年审)相关的技术参数一览
- vsco使用教程_vsco cam怎么用?vsco cam安卓版使用教程详解
- python语句中print(type(1j))_Python语句 print(type(1/2))的输出结果是:______
- 关于BP神经网络模型的学习思考
- 神经网络为什么需要加偏置项(bias)?
- 西门子200smart,MODBUS RTU轮训实例
- web服务器的.do文件是什么,.do是什么文件
- linux dota 中文名,Ubuntu等Linux系統下用Steam運行Dota 2及Left 4 Dead 2等遊戲時,中文字符變成小方塊的解決辦法...
- python三维图形渲染-Python 竟能绘制如此酷炫的三维图
- 慕尼黑工业大学自动驾驶课程
热门文章
- oracle控制文件还原,Oracle的控制文件的恢复与重建
- 小米互联通信服务_时隔六年,小米NFC碰碰贴复活,碰一下自动亮灯、联网、投屏...
- 【爬虫剑谱】三卷2章 拾遗篇-有关于re库的使用小结
- 系统运行缓慢的问题定位步骤
- llinux文本三剑客之grep、egrep及相应的正则表达式和用法
- 在windows 服务中 调打印_Windows打印后台处理程序漏洞(CVE20201048)
- CentOS 7 安装 JAVA环境(JDK 1.8)
- scheduled只执行一次,有个定时任务突然不执行了?
- oracle中rownum的三种分页方式
- log4j的日志级别