【发布时间】:2021-03-17 17:09:31
【问题描述】:
我有一个 txt 文件,其中包含以下数据集作为列表
Name:AP_A
Ch:0
Ptx:20
CCA:-68
AvgThroughput:{}
Data packets_sent:{}
Data_packets lost:{}
rts_cts_sent:{}
rts_cts_lost:{}
in-degA:0.0006766529737718963
out-degA:1.1814245426625214
-----------------
Name:AP_B
Ch:0
Ptx:5
CCA:-90
AvgThroughput:{}
Data packets_sent:{}
Data_packets lost:{}
rts_cts_sent:{}
rts_cts_lost:{}
in-degB:1.6025829114087657
out-degB:0.0006766529737718963
我需要搜索这些行/单词并将它们作为下一个数据集
---AP_A data---
Name:AP_A
in-degA:0.0006766529737718963
out-degA:1.1814245426625214
---AP_B data---
Name:AP_B
in-degB:1.6025829114087657
out-degB:0.0006766529737718963
我有一个代码来做这个,但我不能让我描述
archivo_ficha= "ficha_nodos_triang28.txt"
with open(archivo_ficha,'r') as inputfile:
lines = []
for line in inputfile:
lines.append(line)
search_words1=['Name:AP_A','in-degA','out-degA','Name:AP_B','in-degB','out-degB']
for line in inputfile:
if any(word in line for word in search_words1):
print("---datos_NodoA---")
print(line)
print("---datos_NodoB---")
print(line)
提前致谢
【问题讨论】:
-
您是否只想打印数据?您可以使用 grep:
grep -E '^(Name|(in|out)-deg[AB]):' filename做到这一点,并且几乎完全符合您的要求。 -
嗯,是的,我需要把它放在控制台屏幕上,但也要把它作为一个变量,以便以后使用该数据,感谢您的贡献伙伴
标签: python string search readlines txt