snippsat 661 Master Poster

One soultion with regular expression,not hard to wirte regex for this just a couple of min.

import re

text = '''\
"Id","File","Easting","Northing","Alt","Omega","Phi","Kappa","Photo","Roll","Line","Roll_line","Orient","Camera"
1800,2008308_017_079.tif,530658.110,5005704.180,2031.100000,0.351440,-0.053710,0.086470,79,2008308,17,308_17,rightX,Jen73900229d
1801,2008308_017_080.tif,531793.060,5005709.230,2033.170000,0.385000,-0.044790,-0.057690,80,2008308,17,308_17,rightX,Jen73900229d
1802,2008308_017_081.tif,532930.810,5005709.150,2032.250000,0.350180,-0.044950,0.271100,81,2008308,17,308_17,rightX,Jen73900229d
1803,2008308_017_082.tif,534066.230,5005706.620,2037.630000,0.345480,-0.036860,0.234700,82,2008308,17,308_17,rightX,Jen73900229d
1804,2008308_017_083.tif,535212.280,5005706.990,2037.470000,0.336650,-0.045540,0.306690,83,2008308,17,308_17,rightX,Jen73900229d
'''

test_match = re.findall(r'\d{7}\_\d{3}\_\d{3}\.\btif\b',text)
print test_match #Give us a list

#Looping over item in list
for item in test_match:
    print item

'''-->Out
['2008308_017_079.tif', '2008308_017_080.tif', '2008308_017_081.tif', '2008308_017_082.tif', '2008308_017_083.tif']
2008308_017_079.tif
2008308_017_080.tif
2008308_017_081.tif
2008308_017_082.tif
2008308_017_083.tif
'''
snippsat 661 Master Poster

In order for my code to be efficient, loops need to be terminated prematurely to prevent unnecessary iterations

Yes list comprehension are faster than ordinary loop,but dont do to much Premature optimization.

One of the frequently repeated mantras I hear from Python veterans is, "Premature optimization is the root of all evil"

So first write your code in a readable and clear way,before doing to much optimization.
If exception handling with list comprehension is to difficult then dont do it.

Learn to test your code,dont relay on that some code is faster than other code.
More on this later.

To your code.

try:
    print [x if x < 3 else 1/0 for x in range(5)]
except: #Dont ever do this
    pass
#Now this code should break and user dont know anything, no message is coming

#Test in IDLE
>>> print [x if x < 3 else 1/0 for x in range(5)]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 

try:
    print [x if x < 3 else 1/0 for x in range(5)]
except ZeroDivisionError:
    #Always give message to user
    print 'And ZeroDivisionError has happend'

'''-->ZeroDivisionError has happend'''

So write it without list comprehension.

try:
    l= []
    for x in range(5):
        if x < 3:
            l.append(x)
        else:
            1/0
except ZeroDivisionError:
    #Always give message to user
    print 'ZeroDivisionError has happend'
print l
'''-->ZeroDivisionError has happend
[0, 1, 2]
'''

So we test the code …

snippsat 661 Master Poster

Just one small thing is that it is quite rare for the filename to end with with both .txt and .jpg, so I would fix logic little:

See the 2 previos post i just copy that list,and i think most understand it`s just used as an example.

does it. .tar.gz file is however gz file, not tar file

This will check for gz file.

aFile = 'file.tar.gz'
for ext in ['.rar', '.gz', '.zip']:
    if aFile.lower().endswith(ext):
        print 'Do something'

There are many way do this,i think this is quit readable.
"Readability counts" as taken out from the zen of python.
http://www.python.org/dev/peps/pep-0020/

snippsat 661 Master Poster

Here is an alternative with "endswith" thats works fine for this.

aFile = 'test.jpg'
for ext in ['.txt', '.jpg', '.zip']:
    if aFile.lower().endswith(ext):
        print 'Do something'
snippsat 661 Master Poster

Now it will match any text,so if your file start with asms or psms
It will do the same as my pervious post.

If there are are gap more than 1 space you mean as postet by vega,specify this better.

import re

#Open file for write
fout1 = open('join.txt', 'w')

for item in open('my_file.txt'):
    test_match = re.findall(r'.',item,re.IGNORECASE)   
    if item.startswith(str(test_match)) or '\n':
        a = item.replace(' ', '')
        fout1.writelines(a)
fout1.close()
snippsat 661 Master Poster

Here i use startswith('s') to get it to work on first line.
Then or to ger it to replace whitspace in everey new line \n.

This is an efficient way because you dont read hole file into memory,it work line by line.
Off course on small file this dosent matter to much.

#Open file for write
fout1 = open('join.txt', 'w')

for item in open('my_file.txt'):
    if item.startswith('s') or '\n':
        a = item.replace(' ', '')
        fout1.writelines(a)
fout1.close()

'''
join.txt
ssmssmsmsms
sksksskkksppppplkl
ndndndndkdkdkdkdkppp
'''
snippsat 661 Master Poster

You dont need a new except for every excption you whant to catch.
Could look something like this.

try:   
    file = t1.get()
    py_compile.compile(file)
except (IOError,UnicodeDecodeError,SyntaxError):
    #Give message
else:
    print "That went well!"
finally:
    print "Cleaning up."
snippsat 661 Master Poster

Python 3.x version after run through 2to3 module.

import pprint

info ="101;johnny 'wave-boy' Jones;USA;8.32;Fish;21"
stat = 'id,name,country,average,board,age'

info = info.split(';')
stat = stat.split(',')

my_Dict = {}

k = 0
for item in stat:
    my_Dict[item] = info[k]
    k += 1
    
pprint.pprint(my_Dict)
  
print('*'*35)    

#Sort by key
key_sort = sorted(list(my_Dict.items()), key=lambda v_k: (v_k[0],v_k[1]))
for info, stat in key_sort:
    print('%-10s  %10s' % (info, stat))
    
print('*'*35)

#Sort by value
value_sort = sorted(list(my_Dict.items()), key=lambda k_v: (k_v[1],k_v[0]))
for info, stat in value_sort:
    print('%-10s  %10s' % (info, stat))
snippsat 661 Master Poster

It`s better if you can use a for loop for key:value in a dicitionary.
Than just 6 print statement.

Here some code you can look at,with som sorted output that i see you asked about in an other post.

import pprint

info ="101;johnny 'wave-boy' Jones;USA;8.32;Fish;21"
stat = 'id,name,country,average,board,age'

info = info.split(';')
stat = stat.split(',')

my_Dict = {}

k = 0
for item in stat:
    my_Dict[item] = info[k]
    k += 1
    
pprint.pprint(my_Dict)
  
print '*'*35    

#Sort by key
key_sort = sorted(my_Dict.items(), key=lambda (v,k): (v,k))
for info, stat in key_sort:
    print '%-10s  %10s' % (info, stat)
    
print '*'*35

#Sort by value
value_sort = sorted(my_Dict.items(), key=lambda (k,v): (v,k))
for info, stat in value_sort:
    print '%-10s  %10s' % (info, stat)


##Out
{'age': '21',
 'average': '8.32',
 'board': 'Fish',
 'country': 'USA',
 'id': '101',
 'name': "johnny 'wave-boy' Jones"}
***********************************
age                 21
average           8.32
board             Fish
country            USA
id                 101
name        johnny 'wave-boy' Jones
***********************************
id                 101
age                 21
average           8.32
board             Fish
country            USA
name        johnny 'wave-boy' Jones
snippsat 661 Master Poster

A one liner i came upp with for fun.

print 'List has duplicate item %s' % [item for item in set(L) if L.count(item) > 1]
'''List has duplicate item ['oranges']'''
snippsat 661 Master Poster

Do you have a question?
If this is a school task try to code something yourself.

What you have now is pseudocode,that maybe has some info to this task that we dont know.

snippsat 661 Master Poster

time.sleep(10000000)is a vey long time and will give an error message.
OverflowError: sleep length is too large

time.sleep(5) #wait for 5sec
You can try this

import time
abc = [1,2,6,2,4,2,4,6,3,43,6]
print 'hey%s' % abc
time.sleep(5)
print 'What not again %s' % abc
snippsat 661 Master Poster
IDLE 2.6.5      
>>> abc = [1,2,6,2,4,2,4,6,3,43,6]
>>> print 'hey%l'%abc

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    print 'hey%l'%abc
ValueError: incomplete format
>>> print 'hey %s' % abc
hey [1, 2, 6, 2, 4, 2, 4, 6, 3, 43, 6]
>>>
snippsat 661 Master Poster

Off course python doc has info about this.
This is very basic off any language.

You can look at this.

i = 55
print i
print(type(i))  

s = 'hello'
print s
print(type(s)) 

l = [1, 2, 3]
print l
print(type(l))  

print('string say %s i am an integer %d this is a list %s' % (s, i, l))

'''-->Out
55
<type 'int'>
hello
<type 'str'>
[1, 2, 3]
<type 'list'>
string say hello i am an integer 55 this is a list [1, 2, 3]
'''
snippsat 661 Master Poster

but what do they mean with this: directory[last,first] = number

Test it out

IDLE 2.6.5      
>>> directory = {}  #Empty  dictionary
>>> last = 'hansen'
>>> first = 'tom'
>>> number = 22558899
>>> directory[last,first] = number
>>> directory
{('hansen', 'tom'): 22558899}
>>> 
>>> dir(directory)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> #Here you see methods under dictionary
>>> directory.keys()
[('hansen', 'tom')]
>>> #So first last is a tuple key in the dictionary
>>> directory.values()
[22558899]
snippsat 661 Master Poster

Just to show an alterntive print line with string formatting.
Now you see it find car one time.
Try to change the code so it find both cases off car in the text.

text = '''I like to drive my car.
My car is black.'''    

search_word = 'car'
index = text.find(search_word)
if index == -1:
    print "Nothing found"
else:
    print "%s found at index %s" % (search_word, index)

'''-->Out
car found at index 19
'''
snippsat 661 Master Poster
snippsat 661 Master Poster

Some fun.

import re
print 'Word found was found %s times' % (len([re.findall(r'\bhi\b',open('my_file.txt').read())][0]))

Or a more readable version.

import re

Search_word = 'hi'
comp = r'\b%s\b' % Search_word
my_file = open('my_file.txt').read()
find_word = re.findall(comp, my_file)
print 'Word was found %s times' % len(find_word)
snippsat 661 Master Poster

Have you read at Pygame news? I cannot tell if they are going to abandon Pygame but they are heading on JS. If they are abandoning Python I would not bother learning it. I would look at other modules or Move to another language.

pygame rewritten for javascript - Apr 1, 2010

The date give you a hint.

snippsat 661 Master Poster

First you can start to dowload a picture from web.

2. Download found Images (urllib2?)

Yes can use urllib2.

I have been thinking off makeing a Image crawler for a while now and maybe with a gui frontend(wxpython)
Just havent getting startet yet.

Here some code you can look at,download a random picture i found on net and save it to disk.

from urllib2 import urlopen

def download_from_web(url,outfile):
    '''
    Give url adress to source you want to download
    Name of fileformat example <somthing.jpg>
    '''    
    try:
        webFile = urlopen(url)
        localFile = open(outfile, 'wb')
        localFile.write(webFile.read())
        webFile.close()
        localFile.close()
    except IOError, e:
        print "Download error"
        
def main():
    #Just a random picture
    download_from_web('http://www.opticianonline.net/blogs/big-optometry-blog/Optyl.jpg','myfile.jpg')        
        
if __name__ == "__main__":
    main()
snippsat 661 Master Poster

Fix your indentations(4 space)
Python will not work with wrong indentations.
Shall look like this.

def __init__(self, image, x, y):
    self.image= image
    self.xPos=x
    self.yPos=y
    self.dir=1

If you dont know this,read some basic lesson before you try pygame.
Like byte og python

snippsat 661 Master Poster

You can simplifying your code as suggest på vegaseat.

Think about design,now you have one long main function.
This make code hard to read and if you want to add more code this will soon get difficult.

Split code upp in more function.
A shorter function is eaiser to test and read.
A function keep code local,so you can use in and other code if you need that later.

Just some code to show you what i mean.

import random

def read_in_file():
    shuffle_txt = open("kn.txt", "r").readlines()
    random.shuffle(shuffle_txt)
    return shuffle_txt

def do_domething(arg):
    '''This is a dok string you can explain what this function do'''
    my_list = arg  
    print my_list  #Just a test print to show how you can get data in from read_in_file()
    
def main():
    while True:
        print '(1)play Knock game'
        print '(2) Quit'
        choice = raw_input('Enter your choice: ') 
        if choice == '1':
            shuffle_txt = read_in_file()
            do_domething(shuffle_txt)           
        elif choice == '2':            
           return       
        else:
            print 'Not a correct choice:', choice        
        
if __name__ == "__main__":
    main()
snippsat 661 Master Poster

Kur3k that code will break because your exception handling is wrong.
The code dos not what what is ask for.
It check if an integer for odd/even and has no 'quit' check out.
The code example should like this to make sense.

def check(number):
    if number % 2 == 0:
        return True
    else:
        return False

while True:
      try:
        number = int(raw_input("> Number "))
        if check(number) == True:
            print 'Number did pass it is a even number'
            break
      except ValueError:
        print "Wrong input only numbers,try again"

More like this is what ask for.

my_numbers = []
print 'Enter numbers | calculate <c> quit <q>'
while True:
    try:        
        n = raw_input('Enter a number: ')
        if n.lower() == 'q':
            break        
        elif n.lower() == 'c':
            print sum(my_numbers)
            break
        my_numbers.append(float(n))    
    except ValueError:        
        print 'Please only numbers,try again'
snippsat 661 Master Poster

startswitch/endswith you can use tuple.

if not link.startswith(('javascript','mailto')) and not link.endswith(('pdf','ppt')):
#do something

Depends on how input text is,but a regex can bee used.
Just an untestet regex for this could look something like this. ^javascript|^mailto|pdf$|ppt$ .

Or make variables with tuple as jca0219 suggest.

snippsat 661 Master Poster

Try.
print "You played %s. The computer played %s and %s" % (player_card1, computer_card1, computer_card2)

You can not use a% b% c%
http://docs.python.org/library/stdtypes.html#string-formatting-operations

Most commen formatting expression.
%s == String (converts any Python object using str()).
%d == Signed integer decimal
%f == Floating point decimal format.

snippsat 661 Master Poster

Use lowercase for your string formatting expression.

>>> print 'Hi this is a %s' % 'test'
Hi this is a test
>>> print 'Hi this is a %S' % 'test'
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
ValueError: unsupported format character 'S' (0x53) at index 14
>>>
snippsat 661 Master Poster

Dont mix indentations use always 4 space.
Look into function,when you write all in global space it get soon difficult if you want to jump back and fourth between part of the code.

def my_menu():
    menu = """
    Choose the operation to do (1-2):
    1) Add
    2) Substract
    3) Quit
    """
    return menu

def add():
    x = int(raw_input("Give me the first number: "))
    y = int(raw_input("Give me the second number: "))
    print "The result is", (x+y)

def Substract():
    x = int(raw_input ("Give me the first number: "))
    y = int(raw_input("Give me the second number: "))
    print "The result is", (x-y)

def main():
    '''this is called dok string info about function'''
    while True:
        operation = raw_input(my_menu())
        if operation == '1':
            add()
        elif operation == '2':
            Substract()
        elif operation == '3':
            return
        else:
            print 'Not correct input,try again'

if __name__ == '__main__':
    main()

Here you fall back into main when a function is finish.
Then you dont neeed ask this userinput = raw_input ("Want to continue adding?\nA) y\nB) n\n") .
Because user can just type 1 again.

snippsat 661 Master Poster

Thanks. I see what I was missing. When can I use Raw input ?

In python 2.x is best to always use raw_input.
input() is i mix off eval() and raw_input() in python 2.x that return an integer.

Python 3.x has only input() work the same way as raw_input in python 2.x(return a string)
So you may ask,what if a need a integer from user input?

IDLE 2.6.5      
>>> my_input = raw_input('Type something: ')
Type something: test
>>> type(my_input)
<type 'str'>
>>> my_input = raw_input('Type something: ')
Type something: 5
>>> my_input = int(my_input)
>>> my_input
5
>>> type(my_input)
<type 'int'>
>>> #you can make raw_input return an integer
>>> my_input = int(raw_input('Type something: '))
Type something: 8
>>> my_input
8
>>> type(my_input)
<type 'int'>
>>>
snippsat 661 Master Poster

Hint.

lst_1 = ['b','a','c','2','1','3']
lst_2 = ['a','b','3''1','2']

diff_list = sorted([item for item in lst_1 if not item in lst_2])
snippsat 661 Master Poster

And result from my program is not:

Yes it work fine as an alterntive to regex.
But it was ask about how to use that regex and write to a file.

how could I append this code (which seems to be what I need) into yours?

http://www.daniweb.com/forums/post11...ml#post1192186

Many Thanks

Dont now what you mean here.

snippsat 661 Master Poster

You can look at this,did some changes to the regex.
Shoud find valid proxy ok now.

import re

'''-->proxy.txt
202.9945.29.27:80
221.11.27.110:8080
11111.45454.4454.444
114.30.47.10:80
116.52.155.237:80
204.73.37.11255:80
220.227.90.154:8080455
'''
proxy_file = 'c:/test/proxy.txt'

proxy_pattern = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,5}\D'
my_compile = re.compile(proxy_pattern)

file2_read = open(proxy_file, 'r')
new_proxy = open('c:/test/new_proxy.txt', 'w')

for currentline in file2_read:
    match_obj = my_compile.search(currentline)
    if match_obj:        
        print currentline.rstrip()  ##Test print      
        new_proxy.write(currentline)    

file2_read.close()
new_proxy.close()

'''-->new_proxy.txt
221.11.27.110:8080
114.30.47.10:80
116.52.155.237:80
'''
snippsat 661 Master Poster

Somthing like this?

def click(self, val):
        s = "Button %s was clicked" % val
        label = tk.Label(text = s, width = 15)
        label.grid(row = 0, column = 0)        
        s = "Button " + val + " clicked"        
        # show result in title
        self.title(s)
snippsat 661 Master Poster

If you want more advace look dont use tkinter.
Tkinter look ugly under windows(Non-native look-and-feel)

This make me not use tkinter at all,i find wxpyhon som much better an it look good under windows.
Button are rounded in wxpython,or there are easy to make the look you what.
And when you move mouse over button it highlight,this dos not ugly tkinter buttons.

PyQt and PyGTK are also good tool-kit(that dont have native look-and-feel under windows.)

snippsat 661 Master Poster

@ultimatebuster
That regex vil match "456729994744"

import re

test_input = '456729994744'

if re.match(r'(\d{3})\D*(\d{3})\D*(\d{4})', test_input):
    print ('That is a valid input')  #That is a valid input  
else:
    print ('This is not a valid input')

A fix vil be this.
^(\d{3})\D*(\d{3})\D*(\d{4})$

Now it seems as this list only has numbers that shall match on lenght.
So no need to match against nr as (573)8841878 or 322-3223-222.
Then d5e5 solution work fine.

snippsat 661 Master Poster

I can write a solution tomorrow(away now),with regex.
Not so difficult to filter out numbers you need.

snippsat 661 Master Poster

What contry do you what valid phone nummers for?

Or give an example of match and not match.
match-
(+44)(0)20-12341234
02012341234

Not match.
(44+)020-12341234
1-555-5555

snippsat 661 Master Poster

Thanks for responding, how to i test this

def list_sort(input_list,):
'''Sort a list'''
return sorted(input_list)

What do you mean?,like this.

def list_sort(input_list,):
    '''Sort a list'''    
    return sorted(input_list)

my_list = [5,9,6,3,7,4,5]    
print list_sort(my_list)    #[3, 4, 5, 5, 6, 7, 9]

It shoul be clear from my code example.

snippsat 661 Master Poster

can someone please show me how the function of the code should look like.

Thanks in advance

>>> a=[4,2,6,0,7,3,9,21,15,12,17,1,0]
>>> a.sort()
>>> a
[0, 0, 1, 2, 3, 4, 6, 7, 9, 12, 15, 17, 21]
>>>

def list_sort(input_list,):
    '''Sort a list'''    
    return sorted(input_list)
    
def remove_dup(input_list):
    '''Remove duplicate from a list'''
    return set(input_list)

def main():
    '''This is called a doc string'''
    my_list = [5,4,2,8,4]
    
    #First we se what the functions dos
    print list_sort(my_list)
    print remove_dup(my_list)
    print '-'*20     
    
    #Then we can combine them,first remove duplicate then sort    
    remove_duplicate = remove_dup(my_list)
    print list_sort(remove_duplicate)   
    
if __name__ == '__main__':
    main()

'''-->Output
[2, 4, 4, 5, 8]
set([8, 2, 4, 5])
--------------------
[2, 4, 5, 8]
'''

You can look at this.
The code is pretty clear,but just a short explanation because you new to this.

Both function take one argument .
The argument in this case is my_list
When return is done function is finish.
You can change return with print,and call it like this list_sort(my_list) .
Then you just print out result in the function,nothing get returned out.

You see the avantage when using return,you can have many function return jobb you want to do.
And in the main() you can pick upp all data and print it out.

snippsat 661 Master Poster
IDLE 2.6.4      
>>> word = raw_input("Please enter a string:")
Please enter a string:racecar
>>> # raw_input is returing a string so dont use "str"
>>> input_word = "word"
>>> input_word
'word'
>>> #Do you see the error now.
>>> word_rev = word[::-1]
>>> word_rev
'racecar'
>>> if input_word == word_rev:
	print "The word you have enterd is a palindrome"
else:
	print"The word you have entered is not a palindrome"

	
The word you have entered is not a palindrome
#Off course because you are comparing against "input_word" that is "word" not "racecar"

>>> #make it easy
>>> word = raw_input("Please enter a string:")
Please enter a string:racecar
>>> if word == word[::-1]:
	print "The word you have enterd is a palindrome"
else:
	print"The word you have entered is not a palindrome"

	
The word you have enterd is a palindrome
>>>

A function for this could look like this.

def is_palindrome(my_string):    
    return my_string.lower() == my_string[::-1].lower()
snippsat 661 Master Poster

What if i wanted to use xcode with python? Can I?

Yes.
http://zovirl.com/2006/07/13/xcode-python/

snippsat 661 Master Poster

Buy him this book can be smart.
http://www.amazon.com/Hello-World-Computer-Programming-Beginners/dp/1933988495
Has some pygame lesson.

Invent Your Own Computer Games with Python
http://inventwithpython.com/

For more basic i think byte og python i good start,and a smart 12 y/o shold cope with it pretty well.
http://www.swaroopch.com/notes/Python

Non-Programmer's Tutorial for Python 2.6
http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6

And kids like youtube.
http://www.youtube.com/watch?v=4Mf0h3HphEA&feature=channel
http://www.youtube.com/watch?v=RHvhfjVpSdE
http://www.youtube.com/watch?v=0xgn-HKzZes&feature=related

snippsat 661 Master Poster

http://wiki.python.org/moin/IntegratedDevelopmentEnvironments
http://stackoverflow.com/questions/81584

Pyscripter as postet over is good,but work only for windows.
Spe is good editor,work linux,mac osx.

Pydev for Eclipse are the many that like.

I use komodo ide and pyscripter windows.
Komodo ide and spe linux.

I fast way to test out editor is portablepython comes with pyscripter and spe.
Just unpack to hdd and all work,has a lot 3 party module installed to,wxpyhon,pygame......
http://www.portablepython.com/

snippsat 661 Master Poster

How about this.

#Python 3
try:
    input_num = float(input('test: '))
except ValueError:
    print ('Not an integer')

print (input_num)
snippsat 661 Master Poster

When it come to web pages([X]HTML)
Then regular expression may not be the right tool to use.
Read bobince famous answer at stackoverflow.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

For small steady web pages regular expression can work ok.
Python has some really good tool for this like BeautifulSoup,lxml.

For a small wiki pages the solution post here by d5e5 and tonyjv can work fine.
Just to show one in BeautifulSoup.

import BeautifulSoup as bs

html = '''\
==Heading1==
<test>
some text here
</test>

==Heading2==
<test>
even more text
</test>
'''

soup = bs.BeautifulSoup(html)
divs = soup.findAll('test')
children = divs[0].contents
my_data = divs[0].string + divs[1].string
print my_data  #some text here even more text

BeautifulSoup can handle almost any web page even it has a lot of bad html.

You didn't write that awful page. You're just trying to get some data out of it. Right now, you don't really care what HTML is supposed to look like.

Neither does BeautifulSoup paser .

snippsat 661 Master Poster

I encourage a two-spaced indent.

No and no no.

Python programmers should read Pep 8 and try to follow advice that is given there.
Use 4 spaces per indentation level.

snippsat 661 Master Poster

Not needed to write long if/elif/else lopp,for something simple as this.

Question = raw_input("Do you wish to play the Guess a Number Game? [Y/n]: ")
if Question.lower() not in ['y', 'n']:
   print "Not a valid option"
else:
    print 'Do something'
snippsat 661 Master Poster

Is there a way to filter out lines based on the fact that there are 5 integers separated by ' '

Yes you can look into regular expression. ^'\d{5}' a regular expression like this will match.
'12345' and not 12345 | '1234' | '12345 | 'a2345'

snippsat 661 Master Poster

If it faster i dont know,have to measure.
For this i think both solution will work fine.

Postet more as an alternative to your soultion,an show that module fileinput can be used for this.

snippsat 661 Master Poster

You can use module fileinput for this.

import fileinput

for line in fileinput.input("node.txt", inplace=1):
    line = line.strip()
    if not '1 87'in line:
        print line

'''Out--> to node.txt
Node 0 sends packet to 1
Node 0 sends packet to 3
Node 0 sends packet to 5
'''
snippsat 661 Master Poster
#It is a good thing that pyton 3 only has input not raw_input and input as python 2
#Let look a little at it
#I do not use python 3,i wait for 3 party module to be portet to python 3

>>> choice = input('Choose your option: ')
Choose your option: 5
>>> choice
'5'
>>> type(choice)
<class 'str'>
>>> choice + choice
'55'
>>> int(choice) + int(choice)
10

>>> #We can make user input return a interger
>>> choice = int(input('Choose your option: '))
Choose your option: 5
>>> choice + choice
10
>>> type(choice)
<class 'int'>
>>>