Saturday, January 17, 2015

Regular Expressions

As a regular of user of Perl regular expressions I know that this is going to suck, but... here we go. Having no idea what the syntax might be I pulled up this site http://www.tutorialspoint.com/python/python_reg_expressions.htm and it seems simple enough.

Attempt 1:

import re
file_in = open ("Text-1.txt", "r")
file_in_content = file_in.read()
if (re.match("<p><br \/></p>", file_in_content)):
  modified = re.sub("<p><br \/><\/p>", "<p>&nbsp;</p>", file_in_content)
  print modified
else:
  print "Nothing to do"
Worked fine and brought to my attention that indentation is important in Python. I also modified the text to hit my "Nothing to do" statement which worked fine as well. Imports are simple enough which is going to become important in the next part because now I want an html / html parser and I don't want to build my own.



Friday, January 16, 2015

Hello World!

I'm starting with the basic Hello World! I don't really know much about it at this point and don't really have a guide I'm working off of.

Basic Hello World

Attempt 1:
print "Hello World!"
Seems to work just fine.

That was easy enough, but not particularly useful. It was actually an accident that I left off a semi colon, but it doesn't seem to care. I'll have to check for best practices once I get a little bit deeper. Next step, reading and writing from a file. I can't really guess the syntax on this so I'm going to Google it. I went with this site... http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python and it seems to be what I'm looking for.

Read from a file

Attempt 1:

f = open('HelloWorld1.py', 'r')
print f
This did not work and gave me this error <open file 'HelloWorld1.py', mode 'r' at 0x0000000001F120C0> 

I scrolled further down the page, and I'm not sure why that seemed to be an example, but later there is a better one leading to the next attempt.

Attempt 2:


f = open('HelloWorld1.py', 'r')
print f.read()
This worked, printing out my first example.

Scrolling further down the page you find what I was really looking for the read and write how-to snippets of code. So the first example threw me off, but this now looks a lot like Perl with only minor differences.

So now that we can read, lets also write and of course there isn't much point to writing the exact same thing you just read.

Write to a file

Attempt 1:
file_in = open('HelloWorld1.py', 'r')
file_in_content = file_in.read()
file_out = open('TestOut.txt', 'w')
file_out.write(file_in_content + '\n--- A little bit extra ---')
 This works as expected.