2014-03-12 81 views
0

我想要创建一个.py文件,该文件可以打开.txt文档并读取数据,将其拆分为单词,然后我希望能够搜索日期和时间。时间可能会有所不同,可能并不准确,因此可能会在两次之间下降。我想打印搜索日期/时间之前和之后的两行。我想打印匹配前后的行

我用这至今:

temp_list =[] 
open_file = open(temp_data, "r") 
contents = open_file.readlines()[57:] #skipping first 57 lines. 
for i in range(len(contents)): 
words = contents[i].split() 
if (len(words) == 43) and (words[0] == date) and (words[1] < time): #using 43 will read/print only lines that have 43 words in them as they are the lines with important data. 
    print words[0], "|", words[1], "|", words[12], "F" 

我完全新的编码,并到处找,但我还是没能发现任何东西。任何帮助表示赞赏,谢谢!

EDIT(它不会让我张贴因某种原因txt文件的照片,而不用口碑):

2010-10-02 19:00:01.15 M〜d 0 2 1 1 2 1 - 38.4 22.7 3.7 NN 20 -1.1 29.2 0 -99.9 0 24.1 16.0 3 71 0 000 172 0284 0473 0949 1023 0224 0228 0.0 080 13415 3 0710〜0 0 FM

2010-10-02 19:30:00.47 M〜 D 0 2 1 1 2 1 -40.2 21.7 2.3 NN 21 -1.6 29.5 0 -99.9 0 24.1 22.0 3 71 0 000 172 0301 0470 0949 1023 0191 0201 0.0 070 13416 3 0444〜0 0 FM

2010-10- 02 20:00:01.73 M 〜d 0 2 1 1 2 0 -28.6 20.6 2.1 NN 22 -1.8 29.1 -99.9 0 0 24.1 23.9 3 74 0 000 172 0241 0474 0949 1023 0187 0193 0.0 067 13417 1 0003〜0 0 FM

+0

你的代码中的数字57和43是什么意思?编程中通常不鼓励使用“魔术数字”。 – RexE

+0

43是一行中的字数(忽略所有其中没有43个字的行 - 这意味着这些行中没有数据)。 57跳过前57行,因为它没有任何数据。 – user3412431

回答

0

您如果该行匹配,则需要返回True的函数。看起来像你的if声明正在这样做。如果它返回True,则打印行contents[i-2:i+2]

+0

我很困惑如何编写此代码:( 由于整行包含43个不同的单词,因此内容需要是单词0,1和12。 – user3412431

+0

如果您发布了.txt文件,可以更好地理解您的问题 – RexE

+0

txt文件的示例是在原始文章中添加的,每行应该有43个字(由于文本包装在此页面上以空格分隔)。 – user3412431