简体   繁体   English

从python中的文本文件中读取数字

[英]read only numbers from text file in python

I have a text file with the following entries: 我有一个包含以下条目的文本文件:

 Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0

I want only the numbers of each variable as follows: 我只需要每个变量的编号,如下所示:

 -6.352 281.116 -1.0 0.0 0.0

Any suggestions on how to approach this? 关于如何处理此问题的任何建议? I am new to python and couldn't figure a function to work this out. 我是python的新手,无法找到解决此问题的函数。 Any suggestions would be appreciated 任何建议,将不胜感激

So if your text file contains: 因此,如果您的文本文件包含:

Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0
Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0 Y2.249 Z283.923 A3=-1.0 B3=0.0 C3=0.0

You could use the following non-regex approach: 您可以使用以下非正则表达式方法:

def get_value(v):
    try:
        return float(v.split('=')[1])
    except IndexError as e:
        return float(v[1:])

with open('input.txt') as f_input:
    for raw_row in f_input:
        values = map(get_value, raw_row.split())
        print values

Giving you: 给你:

[-6.352, 281.116, -1.0, 0.0, 0.0]
[-6.352, 281.116, -1.0, 0.0, 0.0, 2.249, 283.923, -1.0, 0.0, 0.0]

Say s is the line of your file, you can use lookbehind assertion. s是文件的行,则可以使用后向断言。 ?<= to check for variables! ?<=检查变量!

>>> import re
>>> s
'Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0'
>>> re.findall("(?<=[AZaz])?(?!\d*=)[0-9.+-]+",s)
['-6.352', '281.116', '-1.0', '0.0', '0.0']

If you want to do the same with files, 如果您要对文件进行相同操作,

import re
with open('input file.txt','r') as file:
    for line in file:
        print re.findall("(?<=[AZaz])?(?!\d*=)[0-9.+-]+",line)

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

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