简体   繁体   English

什么是从Python文件中读取内容的更好方法?

[英]What is a better way to readlines from Python file?

This is my python file:- 这是我的python文件: -

TestCases-2
Input-5
Output-1,1,2,3,5
Input-7
Ouput-1,1,2,3,5,8,13

What I want is this:- 我想要的是: -

  • A variable test_no = 2 (No. of testcases) 变量test_no = 2 (测试用例数)
  • A list testCaseInput = [5,7] 列表testCaseInput = [5,7]
  • A list testCaseOutput = [[1,1,2,3,5],[1,1,2,3,5,8,13]] 列表testCaseOutput = [[1,1,2,3,5],[1,1,2,3,5,8,13]]

I've tried doing it in this way: 我试过这样做:

               testInput = testCase.readline(-10)

        for i in range(0,int(testInput)):
            testCaseInput = testCase.readline(-6)
            testCaseOutput = testCase.readline(-7)

The next step would be to strip the numbers on the basis of (',') , and then put them in a list. 下一步是在(',')的基础上去掉数字,然后将它们放在一个列表中。

Weirdly, the readline(-6) is not giving desired results. 奇怪的是, readline(-6)没有给出期望的结果。

Is there a better way to do this, which obviously I'm missing out on. 有没有更好的方法来做到这一点,显然我错过了。

I don't mind using serialization here but I want to make it very simple for someone to write a text file as the one I have shown and then take the data out of it. 我不介意在这里使用序列化,但我想让某人编写一个文本文件非常简单,就像我展示的那样,然后从中获取数据。 How to do that? 怎么做?

I'm not sure if I follow exactly what you're trying to do, but I guess I'd try something like this: 我不确定我是否完全遵循你想要做的事情,但我想我会尝试这样的事情:

testCaseIn = [];
testCaseOut = [];

for line in testInput:
    if (line.startsWith("Input")):
        testCaseIn.append(giveMeAList(line.split("-")[1]));
    elif (line.startsWith("Output")):
        testCaseOut.append(giveMeAList(line.split("-")[1]));

where giveMeAList() is a function that takes a comma seperated list of numbers, and generates a list datathing from it. 其中giveMeAList()是一个函数,它接受逗号分隔的数字列表,并从中生成一个数据集列表。

I didn't test this code, but I've written stuff that uses this kind of structure when I've wanted to make configuration files in the past. 我没有测试这段代码,但是当我想要在过去创建配置文件时,我已经编写了使用这种结构的东西。

A negative argument to the readline method specifies the number of bytes to read. readline方法的负参数指定要读取的字节数。 I don't think this is what you want to be doing. 我不认为这是你想要做的。

Instead, it is simpler to pull everything into a list all at once with readlines() : 相反,使用readlines()将所有内容同时拉入列表更简单:

with open('data.txt') as f:
    full_lines = f.readlines()

# parse full lines to get the text to right of "-"
lines = [line.partition('-')[2].rstrip() for line in full_lines]

numcases = int(lines[0])
for i in range(1, len(lines), 2):
    caseinput = lines[i]
    caseoutput = lines[i+1]
    ...

The idea here is to separate concerns (the source of the data, the parsing of '-', and the business logic of what to do with the cases). 这里的想法是分离关注点(数据的来源,“ - ”的解析,以及如何处理案例的业务逻辑)。 That is better than having a readline() and redundant parsing logic at every step. 这比在每一步都有readline()和冗余解析逻辑更好。

  1. This line has an error: 这一行有一个错误:

     Ouput-1,1,2,3,5,8,13 // it should be 'Output' not 'Ouput 
  2. This should work: 这应该工作:

     testCase = open('in.txt', 'r') testInput = int(testCase.readline().replace("TestCases-","")) for i in range(0,int(testInput)): testCaseInput = testCase.readline().replace("Input-","") testCaseOutput = testCase.readline().replace("Output-","").split(",") 

You can use regex for this and it makes it much easier. 你可以使用正则表达式,这使它更容易。 See question: python: multiline regular expression 看问题: python:多行正则表达式

For your case, try this: 对于您的情况,试试这个:

import re
s = open("input.txt","r").read()
(inputs,outputs) = zip(*re.findall(r"Input-(?P<input>.*)\nOutput-(?P<output>.*)\n",s))

and then split(",") each output element as required 然后根据需要split(",")每个输出元素

If you do it this way you get the benefit that you don't need the first line in your input file so you don't need to specify how many entries you have in advance. 如果您这样做,您将获得不需要输入文件中第一行的好处,因此您无需事先指定您拥有的条目数。

You can also take away the unzip (that's the zip(*...) ) from the code above, and then you can deal with each input and output a pair at a time. 你也可以从上面的代码中取出解压缩(即zip(*...) ),然后你可以处理每个输入并一次输出一对。 My guess is that is in fact exactly what you are trying to do. 我的猜测实际上就是你想要做的事情。

EDIT Wanted to give you the full example of what I meant just then. 编辑想要给你一个我当时的意思的完整例子。 I'm assuming this is for a testing script so I would say use the power of the pattern matching iterator to help keep your code shorter and simpler: 我假设这是一个测试脚本所以我会说使用模式匹配迭代器的力量来帮助保持你的代码更短更简单:

for (input,output) in re.findall(r"Input-(?P<input>.*)\nOutput-(?P<output>.*)\n",s):
  expectedResults = output.split(",")

  testResults = runTest(input)
  // compare testResults and expectedResults ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有一种简单的方法可以从文本文件读取到这个漂亮的汤库 python 脚本? - Is there a simple way to readlines from text file to this beautiful soup lib python script? 有没有更好的方法从Python中的文件中读取元素? - Is there a better way to read an element from a file in Python? 在Python中读取大型文件(52mb)的行,是否更好地迭代行或使用readlines? - Reading large file (52mb) of lines in Python, is it better to iterate the lines or use readlines? `readlines()` 会关闭 python 中打开的文件吗? - Will `readlines()` close the opened file in python? 在文本文件中存储Python实例属性的更好方法是什么? - What is a better way to store Python instance attributes in a text file? Python .txt文件迭代和readlines() - Python .txt file iteration and readlines() 从文件中读取行并转换为 numpy - readlines from file and convert to numpy 有没有更好的方法来解析python文件? - Is there a better way to parse a file in python? 有没有更好的方法从python中的输入文件生成rest api端点? - Is there a better way to generate rest api endpoints from an input file in python? 有没有更好的方法从引用它的 python 堆栈跟踪获取文件? - Is there a better way to get to the file from a python stack trace referencing it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM