简体   繁体   English

在 python 的一行中查找小数

[英]Finding decimal in a line in python

I have a file with multiple lines like these:我有一个包含多行的文件,如下所示:

hello check2check number 1235.67 thanks[4]
also 67907 another number of interest[45]

I am trying to find these numbers (float) in each line (they exist only once per line) but the last string might have integers in square brackets or an integer might exist before (as in check2check shown above)我试图在每一行中找到这些数字(浮点数)(它们每行仅存在一次),但最后一个字符串可能在方括号中包含整数,或者之前可能存在 integer(如上面显示的 check2check 所示)

1235.67
67907
import re

def updates (self, fileHandler,spec):
   for line in fileHandler:
      line_new = line.strip('\n')
      ll = line_new.split()
      l = len(ll)


   for i in range (l-1): 
            delay = re.search('\d*\.?\d+',i)

I keep getting this error:我不断收到此错误:

TypeError: expected string or bytes-like object TypeError:预期的字符串或类似字节的 object

Is this the correct way to look for the numerical values?这是查找数值的正确方法吗?

This for i in range (l-1) iterates over integers.for i in range (l-1)迭代整数。

Use利用

for line in fileHandler:
  match = re.search(r'(?<!\S)\d*\.?\d+(?!\S)', line)
  if match:
    print(match.group())

In your class:在您的 class 中:

def updates (self, fileHandler, spec):
    results = []
    for line in fileHandler:
        match = re.search(r'(?<!\S)\d*\.?\d+(?!\S)', line)
        if match:
            results.append(match.group())
    return results

Remove spec if not needed.如果不需要,请删除spec

One approach could apply一种方法可以适用

  • a regex matching numbers ( (?<= |^)\d+(\.\d+)?(?= |$) ) in your string, using re.findall method使用re.findall方法在字符串中匹配数字( (?<= |^)\d+(\.\d+)?(?= |$) )的正则表达式
  • the cast of each value to the float type, using Python built-in map function将每个值转换为浮点类型,使用 Python 内置map function

on each of your string by iterating using a list comprehension.通过使用列表理解进行迭代,在每个字符串上。

import re

def updates (self, fileHandler,spec):
    return [map(float, re.findall('(?<= |^)\d+(\.\d+)?(?= |$)', line)[0]) for line in fileHandler]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM