2016-07-23 38 views
1

我完全不熟悉編碼。這讓我很難過,我覺得我錯過了一些超級基本的東西,但我無法解決它...Python - 不確定如何在變量名稱中使用計數器?

很簡單,我使用for循環來查看文本文件的每一行。 如果找到空行,我想更新一個計數器。

然後我希望使用計數器信息能夠更改變量名稱,然後將文本文件中的特定行保存到變量名稱中。

因此,在腳本末尾,變量名稱ParagraphXLineX將與文本文件中找到的相應段落對應。

但我似乎無法理解如何使用計數器信息來作出變量。

PARA_COUNT = 1 
LINE_COUNT = 1 

for x in CaptionFile_data.splitlines(): 
    if x != "": #still in existing paragraph 
     (PARA_COUNT_LINE_COUNT) = x #I know this syntax isn't right just not sure what to put here? 
     LINE_COUNT += 1 

    else: #new paragraph has started 
     PARA_COUNT += 1 
     LINE_COUNT = 1 

回答

0

動態創建變量是個不好的做法。您應該使用一個dict或列表,而不是,例如:

paragraphs= {1: ['line1','line2'], 
      2: ['line3','line4']} 

如果你堅持使用變量,您可以使用globals():在你的代碼

>>>globals()['Paragraph1Line1']= 'some text' 
>>>Paragraph1Line1 
'some text' 
0

,您可以使用列表存儲空行:

PARA_COUNT = 0 
LINE_COUNT = 0 
emptyLines = [] 
for x in CaptionFile_data.splitlines(): 
    if x != "": #still in existing paragraph 
     emptyLines.append(x)   
     LINE_COUNT += 1 
    else: #new paragraph has started 
     PARA_COUNT += 1 

--try--

第一行找到空行的各項指標
LEN空行的索引列表是空行數你有數據

emptyLineIndex = [i for i,line in enumerate(CaptionFile_data.splitlines()) if not line] 
numberOfEmpty = len(emptyLineIndex ) 
相關問題