![](/img/trans.png)
[英]how to read a specific set of words in .txt file and generate a randomizer of those words
[英]search specific set of words in .txt file
我有一个 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)
提前致谢
你知道你有数据 A 和数据 B。你知道你从感兴趣的行中得到一个带有“AP_X”或“degX”的字符串。另外,你想打印一个标志来说明你输入了哪些数据。
好吧,您的数据以“名称:AP_X”开头。
您将 A 和 B 的所有“写入”变量设置为 false。 当您第一次遇到“名称:AP_A”时,您打开 write_A,保持 write_B 关闭,打印您的 header,它不会被打印两次(仅当 write_A = False 和“名称:AP_A”在行中时才会导致)然后你写下这些行包含感兴趣的标签。
archivo_ficha= "ficha_nodos_triang28.txt"
with open(archivo_ficha,'r') as inputfile:
write_A = False; write_B = False; out_list = []
for line in inputfile:
if 'AP_A' in line and write_A == False:
out_list.append("---datos_NodoA---"); print (out_list[-1])
write_A = True; write_B = False
if write_A == True and 'AP_A' in line or 'degA' in line:
out_list.append(line.strip()); print (out_list[-1])
if 'AP_B' in line and write_B == False:
out_list.append("---datos_NodoA---"); print (out_list[-1])
write_B = True; write_A = False
if write_B == True and 'AP_B' in line or 'degB' in line:
out_list.append(line.strip()); print (out_list[-1])
inputfile.close()
Output:
---datos_NodoA---
Name:AP_A
in-degA:0.0006766529737718963
out-degA:1.1814245426625214
---datos_NodoB---
Name:AP_B
in-degB:1.6025829114087657
out-degB:0.0006766529737718963
正如PaulProgrammer 所建议的,您可以使用正则表达式。 在 Python 中:
import re
archivo_ficha = "ficha_nodos_triang28.txt"
matches = [re.search(r"(Name|(in|out))(.+)", line) for line in open(archivo_ficha, 'r')]
matches = [m.group() for m in matches if m]
matches
是一个列表,您可以从中提取必要的数据:
['Name:AP_A',
'in-degA:0.0006766529737718963',
'out-degA:1.1814245426625214',
'Name:AP_B',
'in-degB:1.6025829114087657',
'out-degB:0.0006766529737718963']
然后可以将它们分成 3 组,并产生您想要的 output。
re.search
扫描一个字符串,寻找与该模式匹配的 substring。 这里的模式是(Name|(in|out))(.+)
。
Name|(in|out)
表示:
Name
in
或out
(.+)
由特殊字符组成,以匹配字符串的 rest:
.
匹配任何字符(换行符除外)+
匹配前一个字符 ( .
) 1 次或多次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.