Ask for a regex for re.sub in python - python

I have some string like these, there will be 0 or more whitespace before or after =, and there will be 0 or 1 ### comment at the end of the string.
log_File = a.log ### the path for log
log_level = 10
Now I want to replace the string on the right of =. for example, set them to as below:
log_File = b.log ### the path for log
log_level = 40
import re
s="log_File = a.log ### the path for log"
re.sub("(?<=\s)\w+\S+",'Hello",s)
The above code replaces all the strings after = to Hello, I don't want to replace the strings after ###, how can I implement this.

Try following code:
>>> re.sub(r'(?<!#)=(.*?)(?=\s*#|$)', r'= Hello', s, 1)
'log_File = Hello ### the path for log'
Without using regular expression (Inbar Rose's version modified)
def replace_value(s, new):
content, sep1, comment = s.partition('#')
key, sep2, value = content.partition('=')
if sep2: content = key + sep2 + new
return content + sep1 + comment
assert replace_value('log_File = b', ' Hello') == 'log_File = Hello'
assert replace_value('#log_File = b', ' Hello') == '#log_File = b'
assert replace_value('#This is comment', ' Hello') == '#This is comment'
assert replace_value('log_File = b # hello', ' Hello') == 'log_File = Hello# hello'

I don't see where's the problem.
What about the following code ?
import re
pat = '(=\s*).+?(?=\s*(#|$))'
rgx = re.compile(pat,re.MULTILINE)
su = '''log_File = a.log ### the path for log
log_File = a.log
log_File = a.log'''
print su
print
print rgx.sub('\\1Hello',su)
.
EDIT
.
I have seen where's the problem !
As I wrote it, I don't think that the problem can be simply solved by only regex or a relatively simple function, because changing the right-part of an assignement (attribute called value in the AST node of an assignement) without touching the possible comment requires a syntactic analyze to determine what is the left-part of an assignement (attribute called targets in an AST node of an assignement), what is the right-part and what is the possible comment in a line. And even if a line isn't an assignement instruction, a syntactic analyze is required to determine it.
For such a task there's only the module ast, which helps Python applications to process trees of the Python abstract syntax grammar, that can provide the tools to achieve the goal, in my opinion.
Here's the code I succeeded to write on this idea:
import re,ast
from sys import exit
su = '''# it's nothing
import re
def funcg(a,b):\r
print a*b + 900
x = "abc#ghi"\t\t# comment
k = 103
dico["abc#12"] = [(x,x//3==0) for x in xrange(25) if x !=12]
dico["ABC#12"] = 45 # comment
a = 'lulu#88'
dico["mu=$*"] = 'mouth#30' #ohoh
log_File = a.log
y = b.log ### x = a.log
'''
print su
def subst_assign_val_in_line(line,b0,repl):
assert(isinstance(b0,ast.AST))
coloffset = b0.value.col_offset
VA = line[coloffset:]
try:
yy = compile(VA+'\n',"-expr-",'eval')
except: # because of a bug of ast in computing VA
coloffset = coloffset - 1
VA = line[coloffset:]
yy = compile(VA+'\n',"-expr-",'eval')
gen = ((i,c) for i,c in enumerate(VA) if c=='#')
for i,c in gen:
VAshort = VA[0:i] # <== cuts in front of a # character
try:
yyi = compile(VAshort+'\n',"-exprshort-",'eval')
except:
pass
else:
if yy==yyi:
return (line[0:coloffset] + repl + ' ' +
line[coloffset+i:])
break
else:
print 'VA = line[%d:]' % coloffset
print 'VA : %r' % VA
print ' yy != yyi on:'
print 'VAshort : %r' % VAshort
raw_input(' **** UNIMAGINABLE CASE ***')
else:
return line[0:coloffset] + repl
def subst_assigns_vals_in_text(text,repl,
rgx = re.compile('\A([ \t]*)(.*)')):
def yi(text):
for line in text.splitlines():
head,line = rgx.search(line).groups()
try:
body = ast.parse(line,'line','exec').body
except:
yield head + line
else:
if isinstance(body,list):
if len(body)==0:
yield head + line
elif len(body)==1:
if type(body[0])==ast.Assign:
yield head + subst_assign_val_in_line(line,
body[0],
repl)
else:
yield head + line
else:
print "list ast.parse(line,'line','exec').body has more than 1 element"
print body
exit()
else:
print "ast.parse(line,'line','exec').body is not a list"
print body
exit()
return '\n'.join(yi(text))
print subst_assigns_vals_in_text(su,repl='Hello')
In fact, I wrote it accompanied with instructions print and the help of a personnal programm to display an AST tree in a readable manner (for me).
Here after is the code with instructions print only, to follow the process:
import re,ast
from sys import exit
su = '''# it's nothing
import re
def funcg(a,b):\r
print a*b + 900
x = "abc#ghi"\t\t# comment
k = 103
dico["abc#12"] = [(x,x//3==0) for x in xrange(25) if x !=12]
dico["ABC#12"] = 45 # comment
a = 'lulu#88'
dico["mu=$*"] = 'mouth#30' #ohoh
log_File = a.log
y = b.log ### x = a.log
'''
print su
print '#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-'
def subst_assign_val_in_line(line,b0,repl):
assert(isinstance(b0,ast.AST))
print '\n%%%%%%%%%%%%%%%%\nline : %r' % line
print '\nb0 == body[0]: ',b0
print '\nb0.value: ',b0.value
print '\nb0.value.col_offset==',b0.value.col_offset
coloffset = b0.value.col_offset
VA = line[coloffset:]
try:
yy = compile(VA+'\n',"-expr-",'eval')
except: # because of a bug of ast in computing VA
coloffset = coloffset - 1
VA = line[coloffset:]
yy = compile(VA+'\n',"-expr-",'eval')
print 'VA = line[%d:]' % coloffset
print 'VA : %r' % VA
print ("yy = compile(VA+'\\n',\"-expr-\",'eval')\n"
'yy =='),yy
gen = ((i,c) for i,c in enumerate(VA) if c=='#')
deb = ("mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmw\n"
" mwmwmwm '#' in VA mwmwmwm\n")
for i,c in gen:
print '%si == %d VA[%d] == %r' % (deb,i,i,c)
deb = ''
VAshort = VA[0:i] # <== cuts in front of a # character
print ' VAshort = VA[0:%d] == %r' % (i,VAshort)
try:
yyi = compile(VAshort+'\n',"-exprshort-",'eval')
except:
print " compile(%r+'\\n',\"-exprshort-\",'eval') gives error" % VAshort
else:
print (" yyi = compile(VAshort+'\\n',\"-exprshort-\",'eval')\n"
' yyi =='),yy
if yy==yyi:
print ' yy==yyi Real value of assignement found'
print "mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmw"
return (line[0:coloffset] + repl + ' ' +
line[coloffset+i:])
break
else:
print 'VA = line[%d:]' % coloffset
print 'VA : %r' % VA
print ' yy != yyi on:'
print 'VAshort : %r' % VAshort
raw_input(' **** UNIMAGINABLE CASE ***')
else:
return line[0:coloffset] + repl
def subst_assigns_vals_in_text(text,repl,
rgx = re.compile('\A([ \t]*)(.*)')):
def yi(text):
for line in text.splitlines():
raw_input('\n\npause')
origline = line
head,line = rgx.search(line).groups()
print ('#########################################\n'
'#########################################\n'
'line : %r\n'
'cut line : %r' % (origline,line))
try:
body = ast.parse(line,'line','exec').body
except:
yield head + line
else:
if isinstance(body,list):
if len(body)==0:
yield head + line
elif len(body)==1:
if type(body[0])==ast.Assign:
yield head + subst_assign_val_in_line(line,
body[0],
repl)
else:
yield head + line
else:
print "list ast.parse(line,'line','exec').body has more than 1 element"
print body
exit()
else:
print "ast.parse(line,'line','exec').body is not a list"
print body
exit()
#in place of return '\n'.join(yi(text)) , to print the output
def returning(text):
for output in yi(text):
print 'output : %r' % output
yield output
return '\n'.join(returning(text))
print '\n\n\n%s' % subst_assigns_vals_in_text(su,repl='Hello')
I don't give explanations because it would be too long to explain the structure of the AST tree of a code created by ast.parse(). I xwill give some lights on my code if asked
NB there's a bug in the functionning of ast.parse() when it gives the line and column at which begins certain nodes, so I was obliged to correct that byadditional lines of instructions.
For example, it gives a false result on a list comprehension.

Related

No module named 'msvcrt'

I am stuck in here (picture below) and need to pass this in order for it to read my text. Also I have text.txt file. The program itself won't run with python 2. With python 2 it gives me an error in here: print(last_suggestion, end=' ', flush=True).
train_data = 'text.txt'
first_possible_words = {}
second_possible_words = {}
transitions = {}
def expandDict(dictionary, key, value):
if key not in dictionary:
dictionary[key] = []
dictionary[key].append(value)
def get_next_probability(given_list): #returns dictionary
probability_dict = {}
given_list_length = len(given_list)
for item in given_list:
probability_dict[item] = probability_dict.get(item, 0) + 1
for key, value in probability_dict.items():
probability_dict[key] = value / given_list_length
return probability_dict
def trainMarkovModel():
for line in open(train_data):
tokens = line.rstrip().lower().split()
tokens_length = len(tokens)
for i in range(tokens_length):
token = tokens[i]
if i == 0:
first_possible_words[token] = first_possible_words.get(token, 0) + 1
else:
prev_token = tokens[i - 1]
if i == tokens_length - 1:
expandDict(transitions, (prev_token, token), 'END')
if i == 1:
expandDict(second_possible_words, prev_token, token)
else:
prev_prev_token = tokens[i - 2]
expandDict(transitions, (prev_prev_token, prev_token), token)
first_possible_words_total = sum(first_possible_words.values())
for key, value in first_possible_words.items():
first_possible_words[key] = value / first_possible_words_total
for prev_word, next_word_list in second_possible_words.items():
second_possible_words[prev_word] = get_next_probability(next_word_list)
for word_pair, next_word_list in transitions.items():
transitions[word_pair] = get_next_probability(next_word_list)
def next_word(tpl):
#print(transitions)
if(type(tpl) == str): #it is first word of string.. return from second word
d = second_possible_words.get(tpl)
if (d is not None):
return list(d.keys())
if(type(tpl) == tuple): #incoming words are combination of two words.. find next word now based on transitions
d = transitions.get(tpl)
if(d == None):
return []
return list(d.keys())
return None #wrong input.. return nothing
trainMarkovModel() #generate first, second words list and transitions
########## demo code below ################
print("Usage: start typing.. program will suggest words. Press tab to chose the first suggestion or keep typing\n")
import msvcrt #use of mscvrt to get character from user on real time without pressing enter
c=''
sent=''
last_suggestion=[]
while(c != b'\r'): #stop when user preses enter
if(c != b'\t'): #if previous character was tab, then after autocompletion dont wait for user inpput.. just show suggestions
c=msvcrt.getch()
else:
c = b' '
if(c != b'\t'): #dont print tab etc
print(str(c.decode('utf-8')), end=' ', flush=True)
sent = sent + str(c.decode('utf-8')) #create word on space
if(c == b' '):
tkns = sent.split()
if(len(tkns) < 2): #only first space encountered yet
last_suggestion = next_word(tkns[0].lower())
print(last_suggestion, end=' ', flush=True)
else: #send a tuple
last_suggestion = next_word((tkns[-2].lower(), tkns[-1].lower()))
print(last_suggestion, end=' ', flush=True)
if (c == b'\t' and len(last_suggestion) > 0): #print last suggestion on tab
print(last_suggestion[0], end=' ', flush=True)
sent = sent + " " + last_suggestion[0]
I am using Mac and running this in Visual Code and this is the error I get:
baylarbayramov#Baylars-MacBook-Pro markov-predict-next-word-master % python3 -u "markov_nextwordpred.py"
Usage: start typing.. program will suggest words. Press tab to chose the first suggestion or keep typing
Traceback (most recent call last):
File "markov_nextwordpred.py", line 69, in <module>
import msvcrt
ModuleNotFoundError: No module named 'msvcrt'

SHA256 doesn't yield same result

I'm following on this tutorial and in part 2 (picture below) it shows that the SHA256 yields a result different than what I get when I ran my python code:
the string is: 0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
While the tutorial SHA256 comes to: 600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408
My short python shows:
sha_result = sha256(bitconin_addresss).hexdigest().upper()
print sha_result
32511E82D56DCEA68EB774094E25BAB0F8BDD9BC1ECA1CEEDA38C7A43ACEDDCE
in fact, any online sha256 shows the same python result; so am I missing here something?
You're hashing the string when you're supposed to be hashing the bytes represented by that string.
>>> hashlib.sha256('0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'.decode('hex')).hexdigest().upper()
'600FFE422B4E00731A59557A5CCA46CC183944191006324A447BDB2D98D4B408'
You could use Gavin's "base58.py", which I believe he no longer shares it on his github page. However you probably could easily google and find different versions of it from github.
Here is one version edited a little by me:
#!/usr/bin/env python
"""encode/decode base58 in the same way that Bitcoin does"""
import math
import sys
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
__b58base = len(__b58chars)
def b58encode(v):
""" encode v, which is a string of bytes, to base58.
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += ord(c) << (8*i) # 2x speedup vs. exponentiation
result = ''
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == '\0': nPad += 1
else: break
return (__b58chars[0]*nPad) + result
def b58decode(v):
""" decode v into a string of len bytes
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base**i)
result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result
nPad = 0
for c in v:
if c == __b58chars[0]: nPad += 1
else: break
result = chr(0)*nPad + result
return result
try:
import hashlib
hashlib.new('ripemd160')
have_crypto = True
except ImportError:
have_crypto = False
def hash_160(public_key):
if not have_crypto:
return ''
h1 = hashlib.sha256(public_key).digest()
r160 = hashlib.new('ripemd160')
r160.update(h1)
h2 = r160.digest()
return h2
def hash_160_to_bc_address(h160, version="\x00"):
if not have_crypto:
return ''
vh160 = version+h160
h3=hashlib.sha256(hashlib.sha256(vh160).digest()).digest()
addr=vh160+h3[0:4]
return b58encode(addr)
def public_key_to_bc_address(public_key, version="\x00"):
if not have_crypto or public_key is None:
return ''
h160 = hash_160(public_key)
return hash_160_to_bc_address(h160, version=version)
def sec_to_bc_key(sec, version="\x80"):
if not have_crypto or sec is None:
return ''
vsec = version+sec +"\x01"
hvsec=hashlib.sha256(hashlib.sha256(vsec).digest()).digest()
return b58encode(vsec+hvsec[0:4])
def bc_key_to_sec(prv):
return b58decode(prv)[1:33]
def bc_address_to_hash_160(addr):
bytes = b58decode(addr)
return bytes[1:21]
if __name__ == '__main__':
if len(sys.argv) > 1:
if sys.argv[1] == '-en':
print b58encode(sys.argv[2].decode('hex_codec'))
if sys.argv[1] == '-de':
print b58decode(sys.argv[2]).encode('hex_codec')
if sys.argv[1] == '-pub':
print public_key_to_bc_address(sys.argv[2].decode('hex_codec'))
if sys.argv[1] == '-adr':
print bc_address_to_hash_160(sys.argv[2]).encode('hex_codec')
if sys.argv[1] == '-sec':
print sec_to_bc_key(sys.argv[2].decode('hex_codec'))
if sys.argv[1] == '-prv':
print bc_key_to_sec(sys.argv[2]).encode('hex_codec')
else:
print ''
print 'Usage: ./base58.py [options]'
print ''
print ' -en converts hex to base58'
print ' -de converts base58 to hex'
print
print ' -pub public_key_to_bc_address'
print ' -adr bc_address_to_hash_160'
print
print ' -sec sec_to_bc_key'
print ' -prv bc_key_to_sec'
print
To answer your specific question, based on above code you could use this command:
hashlib.sha256('0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'.decode('hex_codec')).digest().encode('hex_codec').upper()

Python - WindowName for Compare with List

I am currently blocked on a point of a program in Python.
I wish to compare in a list, the WindowName event to launch directives.
Example:
import win32api
import pyHook
liste = ["Google", "Task"]
if event.WindowName == liste:
Screenshot ()
return True
else:
return False
Complete code, he work:
def OnMouseEvent(event):
global interval
data = '\n[' + str(time.ctime().split(' ')[3]) + ']' \
+ ' WindowName : ' + str(event.WindowName)
data += '\n\tButton:' + str(event.MessageName)
data += '\n\tClicked in (Position):' + str(event.Position)
data += '\n===================='
global t, start_time, pics_names
"""
Code Edit
"""
t = t + data
if len(t) > 300:
ScreenShot()
"""
Finish
"""
if len(t) > 500:
f = open('Logfile.txt', 'a')
f.write(t)
f.close()
t = ''
if int(time.time() - start_time) == int(interval):
Mail_it(t, pics_names)
start_time = time.time()
t = ''
return True
else:
return False
When i edit the code in """ doesn't work :
t = t + data
liste = ["Google", "Task"]
if event.WindowName == liste:
ScreenShot()
He return :
File "C:\Python26\lib\site-packages\pyHook\HookManager.py", line 324, in MouseSwitch func = self.mouse_funcs.get(msg) TypeError: an integer is required
I test this :
HookManager: func = self.keyboard_funcs.get(msg) to: func=self.keyboard_funcs.get( int(str(msg)) )
But is don't work, i think i note all problem.
Thanks for you help in advance :)

Python stange behaviour when acessing list elements

This small scripts makes exactly what I need.
#!/usr/bin/python
import os
import fileinput
import sys
import shutil
import glob
import time
def replaceAll1(files,searchExp,replaceExp):
for line in fileinput.input(files, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
param1 = [1,2,3]
param2 = [1,2,3]
param3 = [1,2,3]
for i in xrange(len(param1)):
for ii in xrange(len(param2)):
for iii in xrange(len(param3)):
os.system("cp -a cold.in input.in")
old_param1 = "param1 = 1"
old_param2 = "param2 = 1"
old_param3 = "param3 = 1"
new_param1 = "param1 = " + str(param1[i])
new_param2 = "param2 = " + str(param2[ii])
new_param3 = "param3 = " + str(param3[iii])
replaceAll1('input.in',old_param1,new_param1)
replaceAll1('input.in',old_param2,new_param2)
replaceAll1('input.in',old_param3,new_param3)
time.sleep(4)
It enters in a configuration file and replaces sequentially the input parameters according to the lists that are accessed by the loop indexes. It is simple a combination of all the three parameters between each other.
# Input file
param1 = 1 # --- Should be [1,2,3]
param2 = 1 # --- Should be [1,2,3]
param3 = 1 # --- Should be [1,2,3]
The problem is that his big brother is not behaving like it. When it loops through the lists, it gets lost in scheme = 2 and puts dissp_scheme = 2 (freezed) when it should be dissp_scheme = 1. I printed out every single variable that goes inside the function replaceAll marked with comments but when I turn on the other calls it mess up everything. Here is the script.
#!/usr/bin/python
import os
import fileinput
import sys
import shutil
import glob
import time
os.chdir(os.getcwd())
# Replaces the input file parameters
def replaceAll(files,searchExp,replaceExp):
for line in fileinput.input(files, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
# Gets a number inside my input file.
def get_parameter(variable,file_name):
f = open(file_name,'r').readlines()
for i in xrange(len(f)):
index = f[i].find(variable)
if index != -1:
pre_found = f[i].split('=')[1]
return pre_found
# Gets the discretization scheme name.
def get_sheme(number):
if number == 1:
return "Simple Centered Scheme"
elif number == 2:
return "Lax-Wendroff Scheme"
elif number == 3:
return "MacCormack Scheme"
elif number == 4:
return "Beam-Warming Scheme"
elif number == 5:
return "Steger-Warming 1st Order Scheme"
elif number == 6:
return "Steger-Warming 2nd Order Scheme"
elif number == 7:
return "Van Leer 1st Order Scheme"
elif number == 8:
return "Van Leer 2nd Order Scheme"
elif number == 9:
return "Roe Scheme"
elif number == 10:
return "AUSM Scheme"
# Gets the dissipation scheme name.
def get_dissip(number):
if number == 1:
return "Pullian Non-Linear dissipation"
elif number == 2:
return "Second difference dissipation"
elif number == 3:
return "Fourth difference dissipation"
elif number == 4:
return "B&W dissipation"
# Generates the density gnuplot scripts.
def gnuplot(variable,pressure_ratio,scheme,dissip_scheme):
#gnuplot('Density',10,get_sheme(3),'Pullian')
# Building name of the output file.
outFileName = variable.lower() + '_ratio' + str(int(pressure_ratio)) + '_' + scheme.replace(" ","") + '_dissp' + dissip_scheme.replace(" ","") + '.tex'
gnuFileName = variable.lower() + '_ratio' + str(int(pressure_ratio)) + '_' + scheme.replace(" ","") + '_dissp' + dissip_scheme.replace(" ","") + '.gnu'
# Build title of the plot
title = 'Analytical vs Numerical | ' + scheme
f = open(gnuFileName,'w')
f.write("set term cairolatex monochrome size 15.0cm, 8cm\n")
f.write('set output "' + outFileName + '"\n')
f.write("set grid\n")
f.write('set xtics font "Times-Roman, 10\n')
f.write('set ytics font "Times-Roman, 10\n')
f.write('set xlabel "x position" center\n')
f.write('set ylabel "' + variable + '" center\n')
f.write('set title "Analytical vs Numerical Results | ' + variable + '" \n')
f.write('set pointsize 0.5\n')
f.write('set key font ",10"\n')
fortran_out_analytical = 'a' + variable.lower() + '.out'
fortran_out_numerical = variable.lower() + 'Output.out'
f.write('plot "' + fortran_out_analytical +'" u 1:2 with linespoints lt -1 lw 1 pt 4 title "Analytical",\\\n')
f.write( '"' + fortran_out_numerical + '" u 1:2 with lines lw 5 title "Numerical"\n')
f.close()
# Generate latex code.
def generate_latex(text_image_file,caption):
latex.write("\\begin{figure}[H]\n")
latex.write(" \centering\n")
latex.write(" \input{" + text_image_file + "}\n")
latex.write(" \caption{"+ caption +"}\n")
latex.write(" \label{fig:digraph}\n")
latex.write("\\end{figure}\n")
latex.write("\n\n")
# -----------------------------------------------------------------------
# Main loop.
# -----------------------------------------------------------------------
pressure_ratios = [5.0]
schemes = [1,2,3]
dissips = [1,2,3]
# Define replace lines for replace all.
scheme_line = "scheme = "
dissip_line = "dissp_scheme = "
# Open Latex export file.
latex = open("bizu.txt",'w')
i = 0
# ratios.
for i in xrange(len(pressure_ratios)):
print "----------------------------------------"
print " + Configuring File for pressure ratio: " + str(pressure_ratios[i])
print "----------------------------------------\n"
# Schemes
for jj in xrange(len(schemes)):
print " + Configuring file for scheme: " + get_sheme(schemes[jj]) + "\n"
for kkk in xrange(len(dissips)):
print " + Configuring file for dissip: " + get_dissip(dissips[kkk])
# We always work with a brand new file.
os.system("rm input.in")
os.system("cp -a cold.in input.in")
# Replace pressures.
p1_line_old = 'p1 = 5.0d0'
rho1_line_old = 'rho1 = 5.0d0'
p1_line_new = 'p1 = ' + str(pressure_ratios[i]) + 'd0'
rho1_line_new = 'rho1 = ' + str(pressure_ratios[i]) + 'd0'
replaceAll('input.in',p1_line_old,p1_line_new)
replaceAll('input.in',rho1_line_old,rho1_line_new)
# Replace discretization scheme.
old_scheme = scheme_line + "1"
new_scheme = scheme_line + str(schemes[jj])
#==========================================================
# This call is messing everything up when scheme turns to 2
#==========================================================
replaceAll('input.in',old_scheme,new_scheme)
# Replace dissipation scheme.
old_dissp_scheme = dissip_line + "1"
new_dissp_scheme = dissip_line + str(dissips[kkk])
print p1_line_old
print new_scheme
print new_dissp_scheme
replaceAll('input.in',old_dissp_scheme, new_dissp_scheme)
time.sleep(3)
# ### Calling program
# os.system("./sod")
#
latex.close()
And the input file that the it works on is:
&PAR_physical
p1 = 5.0d0
p4 = 1.0d0
rho1 = 5.0d0
rho4 = 1.0d0
fgamma = 1.4d0
R_const = 287.0d0
F_Cp = 1004.5
F_Cv = 717.5
/
&PAR_geometry
total_mesh_points = 1001
start_mesh_point = -5.0d0
final_mesh_point = 5.0d0
print_step = 100
/
&PAR_numeric
scheme = 3
iterations = 10000
time_step = 0.0001d0
/
&PAR_dissip
dissp_scheme = 3
dissip_omega = 0.5d0
/
Thank you all !

Why is y not defined?

In this code for some reason the variable y is not defined for the first if statement only. I need to know why it says that y is not defined. Also if you need code for finding WOEID here it is.
import urllib2
def make_word(words):
result = ""
for i in words:
result += i
return result
continents = ['asia', 'north%20america', 'south%20america', 'europe', 'asia', 'australia', 'antarctica']
a = raw_input('Put in a place: ')
a = a.lower()
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % a).read()
f = page.find('Ohio')
if y not in continents:
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if f == -1:
f = page.find('United States')
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if y in continents:
if f == -1:
f = page.find('')
start = page.find('woeid="', f) + 7
print page[start:]
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
You only define y in very specific circumstances:
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
So only if there is a space in a do you produce y.
Don't create a new variable here, and don't URL-encode manually. Use the urllib.quote() function instead:
from urllib import quote
y = quote(a.lower())
You appear to be mixing a and y throughout your code. Perhaps you need to use more meaningful names here:
place = raw_input('Put in a place: ')
place_quoted = quote(place.lower())
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % place_quoted).read()
if place_quoted not in continents:
if ' ' in a: #This conditions fails in your code and the y variable is not initialized/ set.
if y not in continents: # when this line executes, it has no reference for y, throws the error "undefined"
Better initialize a default value at the start of your code.
Eg : y = None (or) handle your variable properly.

Categories

Resources