【问题标题】:Checking next Line to then implement where the line should go to检查下一行,然后实施该行应该去的地方
【发布时间】:2013-04-07 00:15:12
【问题描述】:

我无法弄清楚如何实现一个文本文件,其中的行包含单词行和数字行。我想要尝试做的是读取单词下的行,然后将这些单词保存到列表变量中。

编码新手,请多多包涵。

示例文本文件:

 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 检查下一行而不离开当前行,然后检查下一行应该转到哪个“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]]

在我的逻辑中对我的伪代码的任何帮助都将非常棒,或者任何可以提供帮助的一般情况将不胜感激。

【问题讨论】:

  • @kindall 我喜欢编辑!

标签: python pseudocode


【解决方案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

【讨论】:

  • 谢谢!这很有帮助
猜你喜欢
  • 1970-01-01
  • 2011-02-02
  • 2023-03-11
  • 1970-01-01
  • 2015-04-23
  • 2011-03-22
  • 2020-10-14
  • 2019-11-12
  • 1970-01-01
相关资源
最近更新 更多