Python解析输入文件的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16155494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:53:52  来源:igfitidea点击:

Python Parse lines of input file

pythonparsingpython-2.7

提问by Legen Waitforit Dary

Im a recent graduate who has made some contacts and trying to help one with a project. This project will help evolve into something open source for people. So any help I can get would be greatly appreciated.

我是一名应届毕业生,已经建立了一些联系并试图帮助一个项目。该项目将有助于演变为人们的开源项目。所以我能得到的任何帮助将不胜感激。

Im trying to parse out certain items in a file I have succeeded in parsing out the specific items. I now need to figure out how to attach all the remaining data to another variable in an organized way for example.

我正在尝试解析文件中的某些项目,我已成功解析出特定项目。例如,我现在需要弄清楚如何以有组织的方式将所有剩余数据附加到另一个变量。

file=open("file.txt",'r') 

row = file.readlines()

for line in row:
    if line.find("Example") > -1:
        info = line.split()
        var1 = info[0]
        var2 = info[1]
        var3 = info[2]
        remaining_data = ????

^^^^^^^^^^is my sample code already doing 90% of what i need. I want to get the remaining_data to all go into that variable line by line for.

^^^^^^^^^^ 是我的示例代码已经完成了我需要的 90%。我想让剩余的数据逐行进入该变量。

print remaining_data

output:remaining_data{
    line 1 of data
    line 2 of data
    line 3 of data
    line 4 of data
}

how can I get it organized and going in like that line by line?

我怎样才能像这样一行一行地组织起来?

回答by Meitham

by using a slice

通过使用切片

remaining_data=info[3:]

If you need the indices you could do

如果你需要索引,你可以做

for i, line in enumerate(info[3:]):
    print("{}: {}".format(i, line))

回答by cmd

remaining_data = []
for line in open("file.txt",'r'):
    if line.find("Example") > -1:
        info = line.split()
        var1 = info[0]
        var2 = info[1]
        var3 = info[2]
        remaining_data.append(' '.join(info[3:]))

at the end of the loop, remaining data will have all lines with out the first 3 elements

在循环结束时,剩余的数据将包含所有行而不包含前 3 个元素