2014-06-21 27 views
-3

我有兩個陣列,infileoutfile收件單獨的數組元素,以唯一文件

infile = ['Apple', 'Orange', 'Banana'] 
outfile = ['Applefile', 'Orangefile', 'Bananafile'] 

我搜索readin.txtinfile陣列的每個元素,並且用於容納所述元件的任何行,我做了幾個的東西。這是readin.txt樣子:

Apple = 13 
Celery = 2 
Orange = 5 
Banana = 
Grape = 4 

outfile數組包含我想創建文件的名稱;每個對應於infile中的元素。 infile中的第一個元素對應於outfile中的第一個元素(文件名),依此類推。

我遇到的問題是這段代碼:

for line in open("readin.txt", "r"): 
    for i in infile: 
     if i in line: 
      sp = line.split('=') 
      sp1 = str(sp[1]) 
      def parseline(l): 
       return sp1.strip() if len(sp) > 1 and sp[1].strip() != '' else None 
       for s in outfile:   
        out = parseline(line) 
        outw = open(s, "w") 
        outw.write(str(out)) 
        outw.close() 

在代碼的第一部分,我想搜索readin.txtinfile(的話任何一個即AppleOrange ,和Banana)。然後我希望代碼選擇出現該單詞的整個行。我知道readin.txt中的任何這樣的行將包含一個等號,因此我希望代碼將等號旁邊的行分開,並僅生成等號後面的行。

雖然代碼的最後一部分確實爲outfile中的每個元素創建了單獨的文件,但實際輸出始終對應於infile的最後一個元素。就好像循環中的每個後續步驟都會覆蓋前面的步驟。我覺得我需要看 line的第012個元素,但我不確定如何在Python中執行此操作。任何幫助都會很棒。

編輯的清晰度和有問題重開的希望:

事實上,下面的代碼似乎做正是我想要的:

for line in open("parameters.txt", "r"): 
    for i in infile: 
     if i in line: 
      sp = line.split('=') 
      sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None  
      print sp1 

在命令行中,我得到:

13 
5 
None 

所以這告訴我,代碼的第一部分基本上是做什麼我希望它(雖然也許不是以最有效的方式,所以任何其他建議將不勝感激)。

在這一點上,我希望打印出來的所有信息都被寫入基於outfile數組的單個文件中。即。 13應該被輸入到一個名爲Applefile的文件中,None應該被寫入一個名爲Bananafile等的文件中。這是我遇到麻煩的地方。我知道'outfile'應該被類似地索引,所以outfile的第一個元素對應於infile的第一個元素,但是到目前爲止我的嘗試都沒有奏效。

這是我最近一次嘗試:

for line in open("parameters.txt", "r"): 
    for i in infile: 
     if i in line: 
      def parseline(l): 
       sp = l.split('=') 
       sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None  
       if sp1: 
        out = parseline(line) 
        outw = open(outfile[i], "w") 
        outw.write(line) 
        outw.close() 

在代碼中定義parseline任何越早開始否定某種原因部分代碼的整體。

我不是在尋找答案。我想了解發生了什麼,並能夠弄清楚如何解決它。

+1

你爲什麼在兩個循環中使用'i'?你爲什麼在循環中使用整個'line',而不是'i'?你預計什麼會發生? – jonrsharpe

+0

@jonrsharpe很顯然,因爲我不知道自己在做什麼 - 因此我尋求幫助。我一直在使用Python正好一個星期。一些建設性的批評可能比只是公然嘲笑我更有幫助。 我正在使用整行,因爲我想提取該行的特定信息,而不僅僅是數組中定義的內容。 – user2068783

+0

這不是一個合適的問題。我建議你閱讀[Python教程](https://docs.python.org/2/tutorial/)。 – jonrsharpe

回答

0

創建對應於INFILE

的最後一個元素,因爲INFILE的每一個元素的每一個文件內的實際輸出,你outfile中的每一個元素遍歷並寫入最新的線,所以它有意義的是,你最終會得到包含最後一行的所有文件。由於您INFILE/OUTFILE線對應可以使用的I指數從主INFILE循環搶你OUTFILE希望標籤..喜歡的東西:

for line in open("readin.txt", "r"): 
    for i in infile: 
     if i in line: 
      sp = line.split('=') 
      sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None 
      if sp1: 
       out = parseline(line) 
       outw = open(outfile[i], "w") 
       outw.write(str(out)) 
       outw.close() 
+0

感謝您的回覆。不幸的是,這並不完美。由於你的代碼中沒有定義parseline,所以我嘗試在不同的地方定義它,但這似乎也不起作用。當我運行基本上你在那裏,我沒有得到任何錯誤,但沒有創建的文件。 – user2068783

0

我將其分爲兩個步驟:

def parse_params(filename): 
    """Convert the parameter file into a map from filename to value.""" 
    out = {} 
    with open(filename) as f: 
     for line in f: 
      word, num = map(str.strip, line.split("=")) 
      out[word] = num 
    return out # e.g. {'Celery': '2', 'Apple': '13', 'Orange': '5'} 

def process(in_, out, paramfile): 
    """Write the values defined in param to the out files based on in_.""" 
    value_map = parse_params(paramfile) 
    for word, filename in zip(infile, outfile): 
     if word in value_map: 
      with open(filename, 'w') as f: # or '"{0}.txt".format(filename)' 
       f.write(value_map[word]) 
     else: 
      print "No value found for '{0}'.".format(word) 

process(infile, outfile, "parameters.txt") 

您當前的代碼確實沒有多大意義:

for line in open("parameters.txt", "r"): # iterate over lines in file 
    for i in infile: # iterate over words in infile list 
     if i in line: # iterate over characters in the file line (why?) 
      def parseline(l): # define a function 
       sp = l.split('=') 
       sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None  
       if sp1: 
        out = parseline(line) 
        outw = open(outfile[i], "w") 
        outw.write(line) 
        outw.close() 
# but apparently never call it (why?) 

使用相同的循環variabl在兩個循環ë名字是一個壞主意,你永遠只看到內在價值:

>>> for x in range(2): 
    for x in "ab": 
     print x 


a 
b 
a 
b 

如果您發現某些功能「需要」在一個特定的地方進行定義,它表明你是依靠作用域訪問變量。爲需要的參數定義特定參數和返回值要好得多;它使開發和測試更加容易。

+0

對於每個'文件名'所指的是什麼,我有點困惑。在你的第一個步驟爲你定義的函數,'高清parseparams(文件名)',你能向我解釋如何,你實際上調用parameters.txt沒有明確地寫呢? 我也不能肯定我明白究竟這兩條線都在做: '字,NUM =地圖(str.strip,line.split( 「=」))'' 出[文字] = NUM ' – user2068783

+0

@ user2068783你還記得你聲稱這不是一個基本的教程問題嗎?見例如['DEF parse_params(文件名):'](https://docs.python.org/2/tutorial/controlflow.html#defining-functions),['地圖(str.strip,line.split( 「=」) )'](https://docs.python.org/2/tutorial/datastructures.html#functional-programming-tools),['出[字] = num'](https://docs.python.org/ 2 /教程/ datastructures.html#字典) – jonrsharpe