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

2024-10-13 22:47:50

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

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、以上仅作为参考,希望能够帮助到大家!

猜你喜欢