[英]how to find a string in a text file and print the lines right before and after
[英]Find a string in a text file, and then print the first words of the following lines in Python
我正在尝试在文本文件中找到关键字。 然后,打印以下3行中的前3个单词。
这是我的文本文件的一个示例:
...
NAME SP IPHASW D HRMM SECON ...
ABCD BH YZ A 1236 53.70
EFGH BH XH A 1243 56.80
IJKL SZ TU B 1248 32.30
MNOP SZ RT 1252 18.50
QRST BH DF B 1253 54.40
因此,我想找到字符串“ NAME”,然后打印以下“ ABCD”,“ EFGH”和“ IJKL”。
这是我在Python中的代码:
sfile=open("file.txt")
while True:
line = sfile.readline()
if line.startswith('NAME'):
item1 = sfile.readline()[0:4]
item2 = sfile.readline()[0:4]
item3 = sfile.readline()[0:4]
break
sfile.close()
但这不起作用...
任何帮助,将不胜感激! 谢谢:)
您需要采取的第一步是将文本文件转换为合适的数据结构,我为此选择了字典,也可以使用嵌套列表。
其次,我将各列的名称转换为该词典的键,然后将这些列下的行值分配为该键的值。
dictionary = {}
with open("sample.txt") as sfile:
data = sfile.readlines()
keys = data[0].split()
for k in keys:
#For creating an empty dictionary
dictionary[k] = []
for values in data[1:]:
for i,value in enumerate(values.strip().split()):
dictionary[keys[i]].append(value)
#print dictionary #To review the data structure.
keyword = "NAME"#raw_input("Please enter the keyword:")
print dictionary[keyword][:3]
这行得通,不确定是否是您要的内容。
with open("file.txt", 'r') as sfile:
lines = sfile.read()
rows = lines.split('\n')
for columns in rows:
items = columns.split(' ')
print items[0]
好吧,我已经解决了我的问题!
这是我的解决方案:
sfile=open("file.txt")
data_sfile=sfile.read()
myArray = data_sfile.split('\n')
for i in range(len(myArray)):
if myArray[i].find("NAME ")>=0:
item1 = myArray[i+1]
item2 = myArray[i+2]
item3 = myArray[i+3]
break
item1 = item1 [0:5]
item2 = item2 [0:5]
item2 = item2 [0:5]
sfile.close()
好的,这不是最漂亮的解决方案,但可以!
谢谢你的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.