[Tutor] Newbie Trouble Processing SRT Strings In Text

Matt Varner matt.l.varner at gmail.com
Sat Nov 1 01:08:12 CET 2014


Alan G wrote: "This is a bad idea.  Instead, write your strings directly to o

o.write(s)

Print adds newlines automatically(unless you explicitly suppress
them). But printing to a file is messy compared to writing directly to
the file. (And also means you cant print debug messages while
developing your code!)"

>>> Thank you so much, Alan.  I had the feeling I was making it more difficult on myself.  In fact, before I tried using stdout as a solution, I was getting errors on my syntax because I was (apparently) trying to "call" the list.  I'm sure I was putting syntax in the wrong order...but now I better understand the use of file objects and lists (and strings!).  :D

===

Danny Yoo wrote: "You may want to look at existing parsers that people
have written. https://github.com/byroot/pysrt

>>>  That will definitely help out in the future once I get a little better wrapping my head around programming with Python.  I would like to cut out the middle man (app: Aegisub) if I could...eventually.  Now that my very basic stumbling block is worked out, I can start building on it.  This will likely come in handy.  :)

Danny Yoo wrote: "Rather than immediately print the string, you may
want to accumulate results in a list.  You can then do some processing
on your list of strings."

>>> Indeed, this is what I was trying with:

lns = f.readlines()

I was creating more trouble for myself by not having the basic syntax
order right, and then using stdout tied to my output file, using print
statements that were adding newlines, even though I was trying to edit
them out.

Thank you both again for your time!

This result works perfectly (REMs removed):

f = open('tmp.txt', 'r')
o = open('result.txt', 'w')
lns = f.readlines()
f.close()
for line in lns:
    if ".\n" in line:
        a = line.replace('.\n','.  ')
        o.write(a)
    else:
        a = line.strip('\n')
        o.write(a + " ")
o.close()


More information about the Tutor mailing list