gpt4 book ai didi

python - 在 Python 3 中检查文件列表中的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 11:14:14 24 4
gpt4 key购买 nike

我试图让我的代码遍历文件列表并从每个文件中检索一条信息。列表中有 618 个 .txt 文件,其中 606 个包含我需要的信息。我需要我的代码来检查每个文件是否包含字符串“J magnitude”,如果包含,则检索相关值。如果字符串不存在,我希望添加数字 -99.9,这样我的列表仍然有 618 个项目。

这是我到目前为止编写的代码:

def find_Jmag (files):
mags = []
for each in files:
with open(each) as f:
if "J magnitude" in f:
for line in f:
if "J magnitude" in line:
mag = float((line.split()[4]))
mags.append(mag)
else:
mag = -99.9
mags.append(mag)
return mags
Jmags = np.array(find_Jmag(txtfiles))

我现在得到的输出是:

[-99.9 -99.9 -99.9 ... -99.9 -99.9 -99.9]

这意味着由于某种原因,每个文件都不符合其中有“J星等”的条件,这是不对的。

这是每个文件的样例:

#  ----------------------------------------------------------------------------------

# SpeX prism spectrum of 2MASP J0345432+254023 (J03454316+2540233)

# Originally observed on 2003 Sep 05

# Average resolution = 75

# Originally published in Burgasser & McElwain (2006) AJ, 131, 1007

#

# PLEASE CITE THE ORIGINAL DATA REFERENCE WHEN PUBLISHING OR PRESENTING THESE DATA

#

# Optical spectral type: L0

# Near infrared spectral type: L1+/-1

# J magnitude = 13.997

# H magnitude = 13.211

# Ks magnitude = 12.672

#

# Wavelength (micron) F_lambda (normalized) Noise (normalized as F_lambda)

# ----------------------------------------------------------------------------------

0.657669 0.155371 0.0956746

0.659854 0.0718279 0.0411391

0.662031 -0.0147441 0.0684986

0.664202 -0.0543488 0.0497614

我不确定哪里出了问题,如有任何帮助,我们将不胜感激!

最佳答案

看起来你的 if J magnitude"in f: 检查失败了。与其检查它,不如尝试在 if "J magnitude"in line: 中有一个标志如果找到“J magnitude”,则为 True,如果标志为 False,则执行 mag = -99.9

def find_Jmag (files):
mags = []
for each in files:
with open(each) as f:
is_found = False
for line in f:
if "J magnitude" in line:
is_found = True
mag = float((line.split()[4]))
mags.append(mag)
if not is_found:
mag = -99.9
mags.append(mag)
return mags
Jmags = np.array(find_Jmag(txtfiles))

关于python - 在 Python 3 中检查文件列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54810071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com