Python,用于从两个指定字符串之间的文件中读取信息,而这些字符串可以存在于elsewh中

2024-10-04 03:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,其中包含一些设备的信息。我想提取一些特定设备的信息。我想知道提取哪些信息的方式是在找到特定字符串时。你知道吗

输入文本文件:

Table of Contents:
DeviceA ...... Page..
DeviceA2 ..... Page..
DeviceB ...... page..
DeviceB2...... Page..
Device1 ...... Page..
Device2 ...... Page..
DeviceC ...... Page..

Blah
Blah

[DeviceA, DeviceA2] Parameter Values:
Width = 1u
length = 2u etc...
Other Information

blah

[Device1] Parameter Values:
Width = 5u
length = 5u etc..
Other Information

blah

[DeviceB, DeviceB2] Parameter Values:
Width = 11u
length = 22u etc..
Other Information

blah

[Device2] Parameter Values:
Width = 5u
length = 5u etc..
Other Information

DeviceA, A2 description
Device1,2 description etc

我有一个设备名称的列表,我想为其提取信息。在本例中,我有一个包含[DeviceA,DeviceA2,DeviceB]的列表,我希望以粗体显示输出(因此当设备名称出现时,然后其他信息)。设备的名称稍后可能会再次出现在文本文件中。你知道吗

因此,当选择device name DeviceA或DeviceA2时:输出应该是(可以忽略device name,只需要device name和其他信息之间的信息

[DeviceA, DeviceA2] Parameter Values:
Width = 1u
length = 2u etc...
Other Information

当设备B:

[DeviceB, DeviceB2] Parameter Values:
Width = 1u
length = 2u etc..
Other Information

当出现其他信息时,我尝试拆分整个文件,然后通过解析设备名按设备名拆分。但这总会引起一些问题。有什么建议吗?你知道吗

谢谢:)


Tags: 信息informationparameterpageetcwidthlengthvalues
1条回答
网友
1楼 · 发布于 2024-10-04 03:23:03

这是非常混乱的英语,但如果你只是想文字后 “Parameter Values:”在某些设备的“Other Information”之前,那么string的substring和index方法就是您所需要的。你知道吗

使用index查找所需设备的索引,然后再次使用index(将所需设备的索引作为第二个参数)查找以下“参数值:”,然后再次查找“其他信息”,然后只取子字符串。你知道吗

大致如下:

marker0 = myfile.index("DeviceA")
marker1 = myfile.index("Parameter Values:",marker0)
startpoint = marker1+len("Parameter Values:")
endpoint = myfile.index("Other Information", startpoint)
print("Relevant Information is: "+ myfile.substring(startpoint,endpoint)

当然,您需要将其粘贴到一个函数中,以便为每个设备执行此操作,而且您还需要通过文件开头声明的初始设备,但如果您了解上述操作的原理,那么这应该很容易。你知道吗

相关问题 更多 >