簡體   English   中英

什么是從Python文件中讀取內容的更好方法?

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

這是我的python文件: -

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

我想要的是: -

  • 變量test_no = 2 (測試用例數)
  • 列表testCaseInput = [5,7]
  • 列表testCaseOutput = [[1,1,2,3,5],[1,1,2,3,5,8,13]]

我試過這樣做:

               testInput = testCase.readline(-10)

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

下一步是在(',')的基礎上去掉數字,然后將它們放在一個列表中。

奇怪的是, readline(-6)沒有給出期望的結果。

有沒有更好的方法來做到這一點,顯然我錯過了。

我不介意在這里使用序列化,但我想讓某人編寫一個文本文件非常簡單,就像我展示的那樣,然后從中獲取數據。 怎么做?

我不確定我是否完全遵循你想要做的事情,但我想我會嘗試這樣的事情:

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

其中giveMeAList()是一個函數,它接受逗號分隔的數字列表,並從中生成一個數據集列表。

我沒有測試這段代碼,但是當我想要在過去創建配置文件時,我已經編寫了使用這種結構的東西。

readline方法的負參數指定要讀取的字節數。 我不認為這是你想要做的。

相反,使用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]
    ...

這里的想法是分離關注點(數據的來源,“ - ”的解析,以及如何處理案例的業務邏輯)。 這比在每一步都有readline()和冗余解析邏輯更好。

  1. 這一行有一個錯誤:

     Ouput-1,1,2,3,5,8,13 // it should be 'Output' not 'Ouput 
  2. 這應該工作:

     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(",") 

你可以使用正則表達式,這使它更容易。 看問題: python:多行正則表達式

對於您的情況,試試這個:

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

然后根據需要split(",")每個輸出元素

如果您這樣做,您將獲得不需要輸入文件中第一行的好處,因此您無需事先指定您擁有的條目數。

你也可以從上面的代碼中取出解壓縮(即zip(*...) ),然后你可以處理每個輸入並一次輸出一對。 我的猜測實際上就是你想要做的事情。

編輯想要給你一個我當時的意思的完整例子。 我假設這是一個測試腳本所以我會說使用模式匹配迭代器的力量來幫助保持你的代碼更短更簡單:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM