Проверка следующей строки, чтобы затем реализовать, куда должна идти строка

Мне трудно понять, как реализовать текстовый файл со строками, содержащими как строки слов, так и строки чисел. Что я хочу попробовать, так это прочитать строки под словами, а затем сохранить эти слова в переменной списка.

Новичок в кодировании, так что потерпите меня, пожалуйста.

Пример текстового файла:

 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

Мой вопрос: как я могу сказать python, чтобы он проверил следующую строку, не выходя из моей текущей строки, а затем проверяя, к какому оператору «если» должна перейти следующая строка?

Пример кода: Упрощенный

 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]]

Любая помощь в моей логике с моим псевдокодом была бы фантастической, или вообще все, что может помочь, было бы очень признательно.


person Conor    schedule 15.04.2013    source источник
comment
@kindall, я люблю редактировать!   -  person Conor    schedule 16.04.2013


Ответы (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
person John    schedule 15.04.2013
comment
Спасибо! Это очень помогло - person Conor; 15.04.2013