gpt4 book ai didi

python - 使用 Python3 在文件中搜索字符串,将下一行的结果添加到数组中,然后在下一个字符串处停止

转载 作者:行者123 更新时间:2023-12-04 02:30:54 24 4
gpt4 key购买 nike

我正在使用 Python 3 处理结果文件。该文件的结构是字符串标识符的组合,后跟以下格式的整数值列表:

ENERGY_BOUNDS 
1.964033E+07 1.733253E+07 1.491825E+07 1.384031E+07 1.161834E+07 1.000000E+07 8.187308E+06 6.703200E+06
6.065307E+06 5.488116E+06 4.493290E+06 3.678794E+06 3.011942E+06 2.465970E+06 2.231302E+06 2.018965E+06
EIGENVALUE
1.219034E+00

此文件中可能有 50 组具有唯一标识符的不同数据集。我想做的是编写一个代码来搜索特定标识符(例如 ENERGY_BOUNDS),然后将后面的值读入列表,在下一个标识符处停止(在本例中为 EIGENVALUE)。然后我需要能够操作列表(查找它的长度、打印它的值等)。

我把它写成一个函数,这样当我想搜索不同的标识符时,我可以在我的代码中多次调用它。到目前为止,我所拥有的是:

def read_data_from_file(file_name, identifier):

list_of_results = [] # Create list_of_results to put results in for future manipulation

# Open the file in read only mode
with open(file_name, 'r') as read_obj:

# Read all lines in the file one by one
for line in read_obj:

# For each line, check if line contains the string
if identifier in line:

# If yes, read the next line
nextValue = next(line)
list_of_results.append(nextValue.rstrip())

return list_of_results

在读取标识符后的下一行之前,它工作正常,我一直在研究如何继续读取该行后的结果以及如何让它在下一个标识符处停止。

最佳答案

以下是简单且经过测试的答案。

你犯了两个错误

  1. line 是一个字符串而不是迭代器,所以执行 next(line) 会导致错误。
  2. 找到标识符后,您只是阅读了一行,同时您需要继续阅读,直到出现另一个标识符。

以下是对您的代码进行少量修改后的代码。它还在您的数据上进行了测试

def read_data_from_file(file_name, identifier):
with open(file_name, 'r') as read_obj:
list_of_results = []
# Read all lines in the file one by one
for line in read_obj:

# For each line, check if line contains the string
if identifier in line:
# If yes, read the next line
nextValue = next(read_obj)
while(not nextValue.strip().isalpha()): #keep on reading untill next identifier appears

list_of_results.extend(nextValue.split())
nextValue = next(read_obj)
print(list_of_results)

关于python - 使用 Python3 在文件中搜索字符串,将下一行的结果添加到数组中,然后在下一个字符串处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64226994/

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