Getting error while write into the file using Python - python

I need some help. I am getting some error while concatenating the string using python. The error is given below.
Error:
appstr='<location name="'+ re.escape(location_name) +'"><room id="'+ re.escape(num) + '"><roomname>+'re.escape(rname)'+</roomname><noseats>+'re.escape(seat)'+</noseats><projectorscreen>+'re.escape(projector)'+</projectorscreen><videoconf>+'re.escape(video)'+</videoconf></room></location>'
^
SyntaxError: invalid syntax
I am explaining my code below.
def some(request):
if request.method == 'POST':
serch=request.POST.get('searchby')
location_name = request.POST.get('lname')
rname = request.POST.get('rname')
seat = request.POST.get('seat')
projector = request.POST.get('projector')
video = request.POST.get('video')
num=str(random.randint(100000000000,999999999999))
if serch == 'Default':
doc = m.parse("roomlist.xml")
root=doc.getElementsByTagName("roomlist")
valeurs = doc.getElementsByTagName("roomlist")[0]
element = doc.createElement("location")
element.setAttribute("name" , location_name)
el1 = element.appendChild(doc.createElement("room"))
el1.setAttribute("id", num)
el2=el1.appendChild(doc.createElement("roomname"))
el2.appendChild(doc.createTextNode(rname))
el3=el1.appendChild(doc.createElement("noseats"))
el3.appendChild(doc.createTextNode(seat))
el4=el1.appendChild(doc.createElement("projectorscreen"))
el4.appendChild(doc.createTextNode(projector))
el5=el1.appendChild(doc.createElement("videoconf"))
el5.appendChild(doc.createTextNode(video))
valeurs.appendChild(element)
doc.writexml(open("roomlist.xml","w"))
if serch == 'code':
file1 = open("roomlist.xml","r")
flstr = file1.replace("</roomlist>", "")
appstr='<location name="'+ re.escape(location_name) +'"><room id="'+ re.escape(num) + '"><roomname>+'re.escape(rname)'+</roomname><noseats>+'re.escape(seat)'+</noseats><projectorscreen>+'re.escape(projector)'+</projectorscreen><videoconf>+'re.escape(video)'+</videoconf></room></location>'
wstr = flstr + appstr + '</roomlist>'
file1.close()
wfile=open("roomlist.xml","w")
wfile.write(wstr)
return render(request, 'booking/bmr.html', {})
Here I need to write the the data into one existing file. Please help me to resolve this error.

Related

AttributeError: 'Checkbutton' object has no attribute 'get'

I am new to Tkinter, and am having an issue when submitting the code. I had an error before involving the reset button, but that has since been fixed, but now the code does not submit, giving the error that is in the title
Here is the code in its entirety https://pastecord.com/ujoxixyhob.dpr
I dont think this will help too much, so here I have isolated it to this one part:
def Submit():
name = entry_name.get()
residency = ''
if rbtnValue.get() == 'intl':
residency = 'intl'
if rbtnValue.get() == 'dom':
residency = 'dom'
program = comboProgramming.get()
courses = ''
if cbtnProgramming.get() == 'COMP100':
courses += '(COMP100)'
if cbtnWebDesign.get() == 'COMP213':
courses += '\n(COMP213)'
if cbtnSoftEng.get() == 'COMP120':
courses += '\n(COMP120)'
result = name + '\n' + program + '\n' + residency + '\n' + courses
messagebox.showinfo(title='Information', message=result)
This is where the error says it is. I am hoping to find out the error. Thank you

Flask: Function is not returning any String and getting Internal Server Error 500

I am returning a bunch of strings to Front End using Flask RESTful API. The string is generated after a ML algo runs on the input string and classify this to a predefined Answer. The back-end is in MongoDB.
The code given below was working fine earlier. Ever since I have inserted the following lines (marked as *) it is not returning any value. After debugging I found the error as built-in error: The view function could not return a list.
Below is my code (only relevant part)
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/response/',methods = ['GET','POST'])
def response():
if request.method=='POST':
text_org = request.json['foo']
text = json.loads(json.dumps(text_org))
text = text.lower()
if len(text.split())==0:
return 'Please ask a question'
elif len(text.split())<=3:
resp = ' '.join(['What more would you like to know about', clean_text(text), '? Please be little more specific..'])
return resp
else:
df_to_match = pd.DataFrame({'Slot_Value':tbl_df['slot_value'],'User_In':[clean_text(text)]*len(tbl_df['slot_value'])})
is_match = [process.extract(i, df_to_match['Slot_Value'], limit=3) for i in df_to_match['User_In']]
is_match_ratio = [i for w in is_match for i in w]
if list(is_match_ratio[0]).pop(1) > 65:
#tup = [w for (w,i,n) in is_match_ratio]
x = model.predict([text])
x_t = le.inverse_transform(x) '# *new line
x_t = x_t.tolist() '# *new line
x_f = ' '.join(x_t)
x_f = re.sub('[^A-Za-z0-9,]',' ',x_f) # * new line
y=x_f.replace(' ','').split(',')
slot_value tbl_df.loc[tbl_df.Combi.str.contains(y),'slot_value']
text_clean = clean_text(text) #User Defined Function for Text preprocessing
df_exact = pd.DataFrame({'Slot_Value':slot_value,'User_input':[text_clean]*len(slot_value)})
slot_exact = [process.extract(i, df_exact['Slot_Value'], limit=1) for i in df_exact['User_input']]
slot_exact = ' '.join([n[0] for n in slot_exact[0]])
for i in db_col.find({"slot_value":slot_exact},{"Answer":1,"_id":0}): # querying mongodb with only 'Answer' shall be retrieved
m = json.dumps(i).split('Answer',1)[-1]
resp = m.replace('\\n','<br>').replace('"','').replace(':','').replace('}','')
resp_final = email_url(resp) # * new line
return resp_final
else:
resp = ' '.join(['Sorry I have not understood this, please rephrase the question or'])
return resp
else:
resp = [random.choices(msg)]
return resp
if __name__ == "__main__":
print("**Starting Server...")
app.run(host='0.0.0.0',port=5002, debug=True)
email_url is a UDF that performs some regex and return the variable resp with HTML tags. What I have figured out that all the exceptional cases like text.split()<=3, ' '.join(['Sorry I have not understood ..... ']) are working fine. So this means problem is with new lines as marked *, may be I am missing out anything?
Edit: Few More Information
le: LabelEncoder
model: MultinomialNB()
The above model is used to predict the class for new input as received via text_org = request.json['foo']
I got the solution. I the below line
slot_value tbl_df.loc[tbl_df.Combi.str.contains(y),'slot_value']
instead of y which is a list, I have changed it to ','.join(y)
To enlighten others: le.inverse_transform always produce an array which needs to be converted to list. In the above code snippet y is that list. Hence such error was occurring.

Concatenating strings and referencing

I am actually making a script to postprocess some database.
I want my script to get the path and the name of files when I enter some details (version, option, etc), and it looks like this...
def file_info(version, something, option):
####### This part is the DB
## Version-path
PATH_ver1 = '/ver1'
PATH_something1 = '/something1'
## Name of files, there are bunch of these datas
DEF_ver2_something2 = '/name of file'
DEF_ver2_something1_option4 = '/name of file'
####### Now starts to postprocess
## path setting - other variables also follows this
if version == 'ver1':
PATH_VER = PATH_ver1
elif version == 'ver2':
PATH_VER = PATH_ver2
## Concatenating the paths
PATH_BIN = PATH_TOP + PATH_VER + PATH_TYP + PATH_OPT
## Setting the file name
BIN_file = 'DEF_' + version + '_' + something + '_' + option
return PATH_BIN, BIN_FILE
def main():
version = input("version here")
something = input("something here")
option = input("option here")
output = file_info(version, something, option)
When I enter something, I can get the path of files correctly, but the file name gives the name of variable, instead of '/name of file'.
Also, since my variables have two values, I mean, it is not a one-by-one matching, I think I can't use a dictionary format. Each items have one key (DEF_***), and there are two corresponding values (PATH_BIN and BIN_FILE). How can I solve this?
It sounds like what you need are nested dictionaries:
#!python3.6
####### This part is the DB
PATH_TOP = '/TOP/PATH'
## Version-path
PATH = {'ver1':'/ver1',
'ver2':'/ver2',
'something1':'/something1',
'something2':'/something2',
'' :'',
'opt1':'/opt1',
'opt2':'/opt2',
'opt3':'/opt3',
'opt4':'/Totally/Different/PATH'
}
## Name of files
DEF = {'ver1':{'something1':{'' :'v1s1'
,'opt1':'v1s1o1'
,'opt2':'v1s1o2'
}
,'something2':{'opt2':'v1s2o2'
,'opt3':'v1s2o3'
}
}
,'ver2':{'something1':{'opt1':'v2s1o1'
,'opt2':'v2s1o2'
,'opt4':'v2s1o4'
}
,'something2':{'' :'v2s2'
}
}
}
def file_info(version, something, option):
PATH_BIN = PATH_TOP + PATH[version] + PATH[something] + PATH[option]
BIN_FILE = DEF[version][something][option]
return PATH_BIN, BIN_FILE
def prompt(item,values):
lst = "'" + "','".join(values) + "'"
while True:
selection = input(f'{item}({lst})? ')
if selection in values:
break
print('not a choice')
return selection
def main():
version = prompt('Version',DEF)
something = prompt('Something',DEF[version])
option = prompt('Option',DEF[version][something])
output = file_info(version, something, option)
print(output)
if __name__ == '__main__':
main()
Output:
C:\>test.py
Version('ver1','ver2')? ver1
Something('something1','something2')? some
not a choice
Something('something1','something2')? something2
Option('opt2','opt3')? opt2
('/TOP/PATH/ver1/something2/opt2', 'v1s2o2')
C:\>test.py
Version('ver1','ver2')? ver1
Something('something1','something2')? something1
Option('','opt1','opt2')?
('/TOP/PATH/ver1/something1', 'v1s1')

Why can't I pickle this list?

The purpose of this form is to let users enter a lot of places (comma separated) and it'll retrieve the phone, name, website. Have it working in a python IDE, no problem, but having issues putting it into my webapp.
I'm getting the error Exception Value: Can't pickle local object 'GetNums.<locals>.get_data' at the line where a is assigned. I checked the type of inputText and verified that it is indeed a list. So, I'm not sure why it won't pickle.
def GetNums(request):
form = GetNumsForm(request.POST or None)
if form.is_valid():
inputText = form.cleaned_data.get('getnums')
# all experimental
inputText = inputText.split(',')
def get_data(i):
#DON'T FORGET TO MOVE THE PRIMARY KEY LATER TO SETTINGS
r1 = requests.get('https://maps.googleapis.com/maps/api/place/textsearch/json?query=' + i + '&key=GET_YOUR_OWN')
a = r1.json()
pid = a['results'][0]['place_id']
r2 = requests.get('https://maps.googleapis.com/maps/api/place/details/json?placeid=' + pid + '&key=GET_YOUR_OWN')
b = r2.json()
phone = b['result']['formatted_phone_number']
name = b['result']['name']
try:
website = b['result']['website']
except:
website ='No website found'
return ' '.join((phone, name, website))
v = str(type(inputText))
with Pool(5) as p:
a = (p.map(get_data, inputText))
# for line in p.map(get_data, inputText):
# print(line)
#code assist by http://stackoverflow.com/a/34512870/5037442
#end experimental
return render(request, 'about.html', {'v': a})
It's actually barfing when trying to pickle get_data, which is a nested function/closure.
Move get_data out of GetNums (and agh rename it to snake_case please) and it should work.

SyntaxError: can't assign to operator

I have written the following function to construct a URL query from a base URL.
start_date='03-03-1997'
end_date='10-04-2015'
yf_base_url ='http://real-chart.finance.yahoo.com/table.csv?s=%5E'
index_list = ['BSESN','NSEI']
url = "http://real-chart.finance.yahoo.com/table.csv?s=%5E{}&a=03&b=3&c=1997&d=10&e=4&f=2015&g=d&ignore=.csv".format('BSESN')
def generate_url(index, start_date, end_date):
if (index == 'BSESN') or (index == 'NSEI'):
s_day = start_date.split('-')[0]
s_month = start_date.split('-')[1]
s_year = start_date.split('-')[2]
e_day = end_date.split('-')[0]
e_month = end_date.split('-')[1]
e_year = end_date.split('-')[2]
print('{} {} {} {} {} {}'.format(s_day,s_month,s_year,e_day,e_month,e_year))
url = (yf_base_url.join(index))&a=s_day&b=s_month&c=s_year&d=e_day&e=e_month&f=e_year
return url
I get the following error.
File "get_data.py", line 21
url = (yf_base_url.join(index))&a=s_day&b=s_month&c=s_year&d=e_day&e=e_month&f=e_year
SyntaxError: can't assign to operator
I am trying to figure out why this can't be done.
This line isn't valid Python syntax:
url = (yf_base_url.join(index))&a=s_day&b=s_month&c=s_year&d=e_day&e=e_month&f=e_year
Did you mean to format your string using the .format function and construct a url that way? You'd do that like this:
url = (yf_base_url.join(index)) + "&a={}&b={}&c={}&d={}&e={}&f={}".format(s_day, s_month, s_year, e_day, e_month, e_year)

Categories