1

I'm totally new to coding. And this is killing me, I feel i'm missing something super fundamental but I just can't work it out...

Very simply, I am using a for loop to look at each line of a text file. If a empty line is found, I wish to update a counter.

I then wish to use the counters information to be able to change variable names which will then have the particular line from the text file saved into it.

SO at the end of the script, a variable name ParagraphXLineX will correspond with the appropriate paragraphs as found in the text file.

But I cannot seem to understand how to use a counters information to make a variable.

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
C. Ricker
  • 11
  • 1

2 Answers2

0

It's bad practice to create variables dynamically. You should use a dict or a list instead, for example:

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

If you insist on using variables, you can use globals():

>>>globals()['Paragraph1Line1']= 'some text'
>>>Paragraph1Line1
'some text'
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

in you code, you can use list to store the empty lines:

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--

first line find all the indexes of empty line
len of empty line index list is number of empty lines you have in data

emptyLineIndex = [i for i,line in enumerate( CaptionFile_data.splitlines()) if not line]
numberOfEmpty = len( emptyLineIndex  )
galaxyan
  • 5,944
  • 2
  • 19
  • 43