![](/img/trans.png)
[英]Extract text present in between two strings in a text file using Python
[英]Python for reading information from a file between two specified strings when these strings can be present elsewhere
我有一個文本文件,其中包含某些設備的信息。 我想提取某些特定設備的信息。 我想知道要提取哪個信息的方法是找到特定字符串時。
輸入文字檔:
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]的列表,並且我想以粗體顯示輸出(因此,當顯示設備名稱時,然后顯示“ 其他信息” 。設備名稱稍后可能會再次出現在文本文件。
因此,當選擇設備名稱DeviceA或DeviceA2時:輸出應為(設備名稱可以忽略,只需要設備名稱和其他信息之間的信息 :
[DeviceA, DeviceA2] Parameter Values:
Width = 1u
length = 2u etc...
Other Information
當DeviceB:
[DeviceB, DeviceB2] Parameter Values:
Width = 1u
length = 2u etc..
Other Information
我嘗試在出現“ 其他信息 ”時拆分整個文件,然后通過解析設備名稱按設備名稱拆分。 但這總是會引起一些問題。 有什么建議么?
謝謝 :)
這是非常令人困惑的英語,但是如果您只想在某些設備的“參數值:”之后和“其他信息”之前輸入文本,則需要字符串具有子字符串和索引的方法。
使用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)
當然,您需要將此功能附加到每個設備的函數中,並且還需要通過文件開頭聲明的初始Device,但是如果您了解上述內容的工作原理,這應該很容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.