2013-04-15 30 views
2

我很難找出如何實現具有文本文件的行,其中包含文本行和行數。我想要做的是讀取單詞下的行,然後將這些單詞保存到列表變量中。檢查下一行然後執行行應該去的地方

編程新手請耐心等待。

示例文本文件:

Hello World 
4, 3, 2 
3, 4, 2 
2, 3, 4 
Change the World 
5, 3, 9 
3, 9, 5 
Save the World 
1, 2, 3 

我的僞代碼:

Open File 
Read the First Line 
If the current-line[0] is Letter then: 
    parse the current Line 
    save the parsed to a Word list 
    Go to the next line 
If the current-line[0] is a Number then: 
    parse the current Line 
    save the parsed line in a list 
    read the next line 
    If the next line has another number then: 
     parse line 
     save it to the previous parsed-line list 
     #Keep Checking if the next line begins with a number 
     #if it doesn't and the next line begins with a letter go back up to the previous statement 

我的問題: 我怎麼能告訴蟒蛇檢查與出下一行離開我的當前行,然後檢查其下一行應該去的「if」語句?

示例代碼:簡體

def parse(): 
    return parse 

txtopen = open("txt","r") 
line = txtopen.readline() 
while line: 
    if line[0] is not between 0 or 9:: 
    parse = parse(line) 
    wordlist.append(parse) 
    if line[0] in between 0 and 9: 
    parse = parse(line) 
    list = list.extend(parse) 
    ''' 
    This is where i cant figure out how to read the next line and check 
    ''' 
    finallist = list.append(list) 
    line = txtopen.readline() 

輸出:

wordList : ["Hello Word", "Change the World", "Save the World"] 
    numberList : [[4,3,2,3,4,2,2,3,4],[5,3,9,3,9,5],[1,2,3]] 

我的邏輯中的任何幫助,我的僞代碼將是非常美妙的或一般的東西,可以幫助將不勝感激。

+0

@ kindall我喜歡編輯! –

回答

1

要閱讀下一行,你可以做這樣的事情。

with open("file.txt", 'r') as f: 
    lines = f.readlines() 
    current_line_index = 0 
    next_line = lines[current_line_index + 1] 
    print next_line 

這裏是我如何解決這個問題。

import csv 

word_list = [] 
number_list = [] 

with open("file.txt", 'r') as f: 
    reader = csv.reader(f) 
    for line in reader: 
     if line[0].strip().isdigit(): 
      number_list.append(line) 
     else: 
      word_list.append(line) 

print number_list 
print word_list 
+0

謝謝!這非常有幫助 –