python如何从文本各行中提取数字

时间:2024-10-13 22:47:50

1、我会提取所有字符串中包含的数字。这是更适合为宗旨,正则表达式或isdigit()方法? 例如:line = "hello 12 hi 89"结果:[12, 89]

python如何从文本各行中提取数字

2、 如果你只是想只提取正整数,请尝试以下操作:>>>挢旗扦渌; str = "h3110 23 cat 桃轾庾殇444.4 rabbit 11 2 dog" >>> [int(s) for s in str.split() if s.isdigit()] [23, 11, 2]我认为,这比正则表达式例子三reseasons更好。首先,你并不需要另一个模块,其次它更可读你不需要解析正则表达式迷你lanaguage,第三它是更快(而且可能更Python):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这将无法识别十六进制格式的花车,负整数或整数。如果您不能接受这些限制 CodeGo.net,下面纤细的回答会做的伎俩。

python如何从文本各行中提取数字

3、我是一个正则表达式:>>> import re >>> re.熠硒勘唏findall(r'\d+', 'hello 42 I\'m a 32 string 30') ['42', '32', '30']这也将匹配42从bla42bla。如果只想用字border(空格,句号,逗号)分隔的数字,你\\ B:>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30') ['42', '32', '30']delnan具有良好的点(见:你可以映射int()在列表中的字符串转换为整数。

python如何从文本各行中提取数字

4、我假设你想花车不仅仅是整数,所以我想这样做: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

python如何从文本各行中提取数字

5、以上仅作为参考,希望能够帮助到大家!

© 手抄报圈