(Pymongo) connect/adding relationship with two column from different collections in MongoDB - python

I'm practicing use python to commit rollback MongoDB (Pymongo)
For example, I have two collections, one collection store all amount of money of each user and log collection is saving data of with roll or input money in bank
total_money_collection {"user": "Joy" , "total_money" : 100, "ID" : 999}
log_money_collection {"user": "Joy" , "in_out_put_money" : null , "ID" : 999}
I need a hand for simpler way, maybe there is a short pymongo command,or MongoDB can do such operation that just extract the result is fine etc.
If I input from log_money_collection {"user": "Joy" , "in_out_put_money" : -7 , "ID" : 999},
how can "in_out_put_money" column effect "total_money" column
Expected output:
total_money_collection {"user": "Joy" , "total_money" : 93, "ID" :
999}
This is my code (I made lot of make an unnecessary move, I believe there is a simpler way):
import pymongo
import datetime
import json
from bson.objectid import ObjectId
from bson import json_util
import re
def init_db(ip, db, coll):
myclient = pymongo.MongoClient('mongodb://' + ip + '/')
mydb = myclient[db]
mycol = mydb[coll]
return mydb, mycol, myclient
def Quy_data( mycol , find_values_json , one_or_many_bool):
try:
if one_or_many_bool:
x = []
for y in mycol.find(find_values_json):
x.append(y)
cash_all_value = mycol.find({},{ "Cash_$": 1 })
else:
x = mycol.find_one(find_values_json)
cash_all_value = mycol.find({},{ "Cash_$": 1 })
return x , cash_all_value
except Exception as e:
msg_fail_reason = "error in ins_data function"
return msg_fail_reason
ip_input = input("Enter the ip: ")
exist_DB_name = input("Enter exist DB name: ")
def parse_json(data):
return json.loads(json_util.dumps(data))
try:
exist_coll = input("Enter exist collection (ex: 10_20_cash_all , 10_20_cash_log ): ")
mydb, mycol , myclient = init_db(ip_input, exist_DB_name, exist_coll)
with myclient.start_session(causal_consistency=True) as session:
# Open a transaction session
with session.start_transaction():
# mycol.insert_one({'Name': ' Gosum '}, session=session)
if exist_coll == "10_20_cash_all":
# I set find all ( = find )
one_or_many_bool = True
findvalues_str = input("Enter find data conditions: ")
find_values_json =json.loads(findvalues_str)
x , cash_all_value = Quy_data( mycol , find_values_json , one_or_many_bool )
# if someone want data in json
modified_data_x_json = parse_json(x)
cash_all_value_json = parse_json(cash_all_value)
a = str(cash_all_value_json)
print(modified_data_x_json)
print(type(modified_data_x_json))
print("= = = = = ")
print(a)
print(type(a))
b = re.search("'Cash_$': (.*)", a)
print(b)
except Exception as e:
# Output exception content
print(e)
output for my (I find the user Joy, and try to extract the number after "total_money" then subtract "in_out_put_money")
Enter the ip: localhost
Enter exist DB name: (practice_10_14)-0004444
Enter exist collection (ex: 10_20_cash_all , 10_20_cash_log ): 10_20_cash_all
Enter find data conditions: { "name": "Joy" }
[{'_id': {'$oid': '6348d73be94317989175dc2d'}, 'name': 'Joy', 'ID': 999, 'Age': 23, 'time': {'$date': '2022-10-17T09:11:54Z'}, 'total_money': 100}]
<class 'list'>
= = = = =
[{'_id': {'$oid': '6348d73be94317989175dc2d'}, 'total_money': 100}, {'_id': {'$oid': '6348d73be94317989175dc2e'}, 'total_money': 100}, {'_id': {'$oid': '6348d73be94317989175dc2f'}, 'total_money': 100}, {'_id': {'$oid': '6348d73be94317989175dc30'}, 'total_money': 100}, {'_id': {'$oid': '6348d73be94317989175dc31'}, 'total_money': 100}, {'_id': {'$oid': '635112dea1fa85dd0cfe590b'}, 'total_money': 100}]
<class 'str'>
None
A simple step of commit rollback MongoDB with account money I turn a huge circle to get it, I need a hand for simpler way, maybe there is a short pymongo command,or MongoDB can do so that just extract the result is fine etc

the same concept make ur {"user": "Joy" , "total_money" : 93, "ID" : 999},
the "total_money" become lesser by subtracting them, for sure U can't directly do that, like python (4 - 1 something)....
here is the code:
import pymongo
import datetime
import json
from bson.objectid import ObjectId
from bson import json_util
import re
myclient = pymongo.MongoClient("mongodb://localhost/")
mydb = myclient["(practice_10_14)-0004444"]
# UD_db_data means update
def UD_db_data(mycol , myquery_json, newvalues_json, one_or_many_bool):
if one_or_many_bool == True:
x = mycol.update_many(myquery_json, newvalues_json)
else:
x = mycol.update_one(myquery_json, newvalues_json)
return x
# Quy_data = query find db_data
def Quy_data( mycol ,find_values_json , one_or_many_bool):
try:
if one_or_many_bool:
x = []
for y in mycol.find(find_values_json):
x.append(y)
else:
x = mycol.find_one(find_values_json)
return x
except Exception as e:
msg_fail_reason = "error in ins_data function"
return msg_fail_reason
mycol_one = mydb["10_20_cash_all"]
mycol_two = mydb["10_20_cash_log"]
mycol_3rd = mydb["10_20_cash_info"]
# already store 100$ in bank
# doc_two = {"ID" : 100998 , "Cash_log$" : 5 } # withdraw 5$ from bank
doc_two = input("Enter ID and log amount$: ")
doc_3rd = input("Enter extra info: ")
doc_two_dic = json.loads(doc_two)
doc_3rd_dic = json.loads(doc_3rd)
# doc_3rd = {"note" : "today is good" }
ID_input = doc_two_dic['ID']
print("ur id is :" + str(ID_input))
doc_one = {"ID" : ID_input}
with myclient.start_session() as s:
cash_all_result = mycol_one.find_one(doc_one, session=s)
def cb(s):
try:
while True:
cash_all_result = mycol_one.find_one(doc_one, session=s)
mycol_two.insert_one(doc_two_dic, session=s)
# print( 3/0 )
mycol_3rd.insert_one(doc_3rd_dic, session=s)
print( "now total is :" + str(cash_all_result['Cash_$']) )
Cash_total_int = int(cash_all_result['Cash_$'])
log_int = int(doc_two_dic['Cash_log$'])
if Cash_total_int < log_int:
print("error: withdraw is over ur balance")
break
new_Cash_total = Cash_total_int - log_int
print("now total is :" + str(new_Cash_total))
newvalues_json = { "$set" : {"Cash_$" : new_Cash_total } }
mycol_one.update_one(doc_one , newvalues_json, session=s)
fail_condition_json = {"ok" : 1 , "fail reason" : "no error "}
print(fail_condition_json)
return fail_condition_json
except Exception as e:
fail_condition_json = {"ok" : 0 , "fail reason" : "error raise on start_session()"}
print(fail_condition_json)
return fail_condition_json
s.with_transaction(cb)
I believe I do the calculation with 3 collection's data
and the output is below
Enter ID and log amount$: {"ID" : 100998 , "Cash_log$" : 23 }
Enter extra info: {"note" : "today is no good" }
ur id is :100998
now total is :72
now total is :49
{'ok': 1, 'fail reason': 'no error '}

Related

unable to iterate through loop in python

i have a sql query which basically retrieves coin names and submits an order for each coin.
However, it only submits an order on one coin and fails to loop through the rest, not sure why thats happening .
import sys
**
import pandas as pd
postgreSQL_select_Query = "SELECT base,quote FROM instrument_static where exchange='ftx'"
cursor.execute(postgreSQL_select_Query)
row=([y for y in cursor.fetchall()])
for i in row:
base=i[0]
quote=i[1]
portfolioItems = [
{
'exchange': 'ftx',
'base': base,
'quote': quote,
'amount': 0.01,
},
]
def init():
username = us
password = passwordVal
initialise(clientId, clientSecret, us, password)
if __name__ == "__main__":
init()
result = construct_portfolio_with_params(us, portname, portfolioItems)
print(result)
You need to initialize portfolioItems prior to the loop, and then you can add to it. Try replacing this snippet of code:
...
row=([y for y in cursor.fetchall()])
portfolioItems = []
for i in row:
base=i[0]
quote=i[1]
portfolioItems.append(
{
'exchange': 'ftx',
'base': base,
'quote': quote,
'amount': 0.01,
}
)
...

Parsing logs to json Python

Folks,
I am trying to parse log file into json format.
I have a lot of logs, there is one of them
How can I parse this?
03:02:03.113 [info] ext_ref = BANK24AOS_cl_reqmarketcreditorderstate_6M8I1NT8JKYD_1591844522410384_4SGA08M8KIXQ reqid = 1253166 type = INREQ channel = BANK24AOS sid = msid_1591844511335516_KRRNBSLH2FS duration = 703.991 req_uri = marketcredit/order/state login = 77012221122 req_type = cl_req req_headers = {"accept-encoding":"gzip","connection":"close","host":"test-mobileapp-api.bank.kz","user-agent":"okhttp/4.4.1","x-forwarded-for":"212.154.169.134","x-real-ip":"212.154.169.134"} req_body = {"$sid":"msid_1591844511335516_KRRNBSLH2FS","$sid":"msid_1591844511335516_KRRNBSLH2FS","app":"bank","app_version":"2.3.2","channel":"aos","colvir_token":"GExPR0lOX1BBU1NXT1JEX0NMRUFSVEVYVFNzrzh4Thk1+MjDKWl/dDu1fQPsJ6gGLSanBp41yLRv","colvir_commercial_id":"-1","colvir_id":"000120.335980","openway_commercial_id":"6247520","openway_id":"6196360","$lang":"ru","ekb_id":"923243","inn":"990830221722","login":"77012221122","bank24_id":"262"} resp_body = {"task_id":"","status":"success","data":{"state":"init","applications":[{"status":"init","id":"123db561-34a3-4a8d-9fa7-03ed6377b44f","name":"Sulpak","amount":101000,"items":[{"name":"Switch CISCO x24","price":100000,"count":1,"amount":100000}]}],"segment":{"range":{"min":6,"max":36,"step":1},"payment_day":{"max":28,"min":1}}}}
Into this type of json, or any other format (but I guess json is best one)
{
"time":"03:02:03.113",
"class_req":"info",
"ext_ref":"BANK24AOS_cl_reqmarketcreditorderstate_6M8I1NT8JKYD_1591844522410384_4SGA08M8KIXQ",
"reqid":"1253166",
"type":"INREQ",
"channel":"BANK24AOS",
"sid":"msid_1591844511335516_KRRNBSLH2FS",
"duration":"703.991",
"req_uri":"marketcredit/order/state",
"login":"77012221122",
"req_type":"cl_req",
"req_headers":{
"accept-encoding":"gzip",
"connection":"close",
"host":"test-mobileapp-api.bank.kz",
"user-agent":"okhttp/4.4.1",
"x-forwarded-for":"212.154.169.134",
"x-real-ip":"212.154.169.134"
},
"req_body":{
"$sid":"msid_1591844511335516_KRRNBSLH2FS",
"$sid":"msid_1591844511335516_KRRNBSLH2FS",
"app":"bank",
"app_version":"2.3.2",
"channel":"aos",
"colvir_token":"GExPR0lOX1BBU1NXT1JEX0NMRUFSVEVYVFNzrzh4Thk1+MjDKWl/dDu1fQPsJ6gGLSanBp41yLRv",
"colvir_commercial_id":"-1",
"colvir_id":"000120.335980",
"openway_commercial_id":"6247520",
"openway_id":"6196360",
"$lang":"ru",
"ekb_id":"923243",
"inn":"990830221722",
"login":"77012221122",
"bank24_id":"262"
},
"resp_body":{
"task_id":"",
"status":"success",
"data":{
"state":"init",
"applications":[
{
"status":"init",
"id":"123db561-34a3-4a8d-9fa7-03ed6377b44f",
"name":"Sulpak",
"amount":101000,
"items":[
{
"name":"Switch CISCO x24",
"price":100000,
"count":1,
"amount":100000
}
]
}
],
"segment":{
"range":{
"min":6,
"max":36,
"step":1
},
"payment_day":{
"max":28,
"min":1
}
}
}
}
}
I am trying to split first whole text, but there I met another problem is to match keys to values depending on '=' sign. Also there might be some keys with empty values. For ex.:
type = INREQ channel = sid = duration = 1.333 (to get to know that there is an empty value, you need to pay attention on number of spaces. Usually there is 1 space between prev.value and next key). So this example should look like this:
{
"type":"INREQ",
"channel":"",
"sid":"",
"duration":"1.333"
}
Thanks ahead!
Here, one thing pass for duplicate key about "$sid":"msid_1591844511335516_KRRNBSLH2FS"
import re
text = """03:02:03.113 [info] ext_ref = reqid = 1253166 type = INREQ channel = BANK24AOS sid = msid_1591844511335516_KRRNBSLH2FS duration = 703.991 req_uri = marketcredit/order/state login = 77012221122 req_type = cl_req req_headers = {"accept-encoding":"gzip","connection":"close","host":"test-mobileapp-api.bank.kz","user-agent":"okhttp/4.4.1","x-forwarded-for":"212.154.169.134","x-real-ip":"212.154.169.134"} req_body = {"$sid":"msid_1591844511335516_KRRNBSLH2FS","$sid":"msid_1591844511335516_KRRNBSLH2FS","app":"bank","app_version":"2.3.2","channel":"aos","colvir_token":"GExPR0lOX1BBU1NXT1JEX0NMRUFSVEVYVFNzrzh4Thk1+MjDKWl/dDu1fQPsJ6gGLSanBp41yLRv","colvir_commercial_id":"-1","colvir_id":"000120.335980","openway_commercial_id":"6247520","openway_id":"6196360","$lang":"ru","ekb_id":"923243","inn":"990830221722","login":"77012221122","bank24_id":"262"} resp_body = {"task_id":"","status":"success","data":{"state":"init","applications":[{"status":"init","id":"123db561-34a3-4a8d-9fa7-03ed6377b44f","name":"Sulpak","amount":101000,"items":[{"name":"Switch CISCO x24","price":100000,"count":1,"amount":100000}]}],"segment":{"range":{"min":6,"max":36,"step":1},"payment_day":{"max":28,"min":1}}}}"""
index1 = text.index('[')
index2 = text.index(']')
new_text = 'time = '+ text[:index1-1] + ' class_req = ' + text[index1+1:index2] + text[index2+2:]
lst = re.findall(r'\S+? = |\S+? = \{.*?\} |\S+? = \{.*?\}$|\S+? = \S+? ', new_text)
res = {}
for item in lst:
key, equal, value = item.partition('=')
key, value = key.strip(), value.strip()
if value.startswith('{'):
try:
value = json.loads(value)
except:
print(value)
res[key] = value
you can try regulation in python.
here is what i write, it works for your problem.
for convenience i deleted string before "ext_ref...",you can directly truncate the raw string.
import re
import json
string = 'ext_ref = BANK24AOS_cl_reqmarketcreditorderstate_6M8I1NT8JKYD_1591844522410384_4SGA08M8KIXQ reqid = 1253166 type = INREQ channel = BANK24AOS sid = msid_1591844511335516_KRRNBSLH2FS duration = 703.991 req_uri = marketcredit/order/state login = 77012221122 req_type = cl_req req_headers = {"accept-encoding":"gzip","connection":"close","host":"test-mobileapp-api.bank.kz","user-agent":"okhttp/4.4.1","x-forwarded-for":"212.154.169.134","x-real-ip":"212.154.169.134"} req_body = {"$sid":"msid_1591844511335516_KRRNBSLH2FS","$sid":"msid_1591844511335516_KRRNBSLH2FS","app":"bank","app_version":"2.3.2","channel":"aos","colvir_token":"GExPR0lOX1BBU1NXT1JEX0NMRUFSVEVYVFNzrzh4Thk1+MjDKWl/dDu1fQPsJ6gGLSanBp41yLRv","colvir_commercial_id":"-1","colvir_id":"000120.335980","openway_commercial_id":"6247520","openway_id":"6196360","$lang":"ru","ekb_id":"923243","inn":"990830221722","login":"77012221122","bank24_id":"262"} resp_body = {"task_id":"","status":"success","data":{"state":"init","applications":[{"status":"init","id":"123db561-34a3-4a8d-9fa7-03ed6377b44f","name":"Sulpak","amount":101000,"items":[{"name":"Switch CISCO x24","price":100000,"count":1,"amount":100000}]}],"segment":{"range":{"min":6,"max":36,"step":1},"payment_day":{"max":28,"min":1}}}}'
position = re.search("req_headers",string) # position of req_headers
resp_body_pos = re.search("resp_body",string)
resp_body = string[resp_body_pos.span()[0]:]
res1 = {}
res1.setdefault(resp_body.split("=")[0],resp_body.split("=")[1])
print(res1)
before = string[:position.span()[0]]
after = string[position.span()[0]:resp_body_pos.span()[0]] # handle req_body seperately
res2 = re.findall("(\S+) = (\S+)",before)
print(res2)
res3 = re.findall("(\S+) = ({.*?})",after)
print(res3)
#res1 type: dict{'resp_body':'...'} content in resp_body
#res2 type: list[(),()..] content before req_head
#res3 type: list[(),()..] the rest content
and now you can do what you want to do with the data(.e.g. transform it into json respectively)
Hope this is helpful

Accessing Nested Dictionaries-Student Data

Below is the code I have tried, actually I am looking for result like comparision of each key dictionary so my max_value for each dictionary will be like "2539:Mark:35" … same thing for rest other dictionary pls help me here to solve this..
student_data = {2539:{'James':30, 'Mark': 35}, 8214: { 'Michelle': 32,'Mark': 40},7411:{'Travis':28, 'Mark': 45}}
for id,v in student_data.items():
print(id, '-->', student_data[id][0] + ',', max(student_data[id][1].values()))
print('Subjects:', student_data[id][2], '\n')
Using your code as much as possible.
Use find max in dictionary to find key with max value in dictionary
Code
student_data = { 2539: { 'James': 30, 'Mark': 35 }, 8214: { 'Michelle': 32,'Mark': 40 }, 7411: { 'Travis': 28, 'Mark': 45 } }
for id,v in student_data.items(): # v is a dictionary
max_student = max(v, key=v.get) # student name with max
print(f'{id}:{max_student}:{v[max_student]}')
Output
2539:Mark:35
8214:Mark:40
7411:Mark:45
Expanded to input info for student_data
def get_parameter(prompt, type_input='str'):
" Used for getting student id, name or score "
while True:
param = input(prompt)
if not param:
return None # done entering
if type_input=='int':
if param.isdigit():
return int(param)
else:
print('Value should be integer')
elif type_input == 'str':
if param.isalpha():
# string so okay
return param
else:
print('Value should be single word string')
# Get student data as list of stuples
# [(id1, name1, score1), (id2, name2, score2), ...]
while True:
id = get_parameter('Student id (blank line to close entries):', 'int')
if not id:
break # break inputting data on blank line
name = get_parameter('Student name: ')
if not name:
break
score = get_parameter('Student score: ', 'int')
if not score:
break
data.append((id, name, score))
# Convert list of tuples to student_data dictionary
student_data = {}
for id, name, score in data:
if not id in student_data:
student_data[id] = {} # add dictionary for id
# Add score and name
student_data[id][name] = score
# Show results
for id,v in student_data.items():
max_student = max(v, key=v.get )
print(f'{id}:{max_student}:{v[max_student]}')

Django/Python Multiple records

I have a program that compares values from the database and from a CSV file. My program works like this.
Database has values.
User uploads a file (multiple users multiple
files).
The program compares the values from the database and the
CSV files and gives an output.
Which tells me that this particular value was found in this user's file.
But I want the program to show me that if the value was found in the other user's file or not.
Here is a working example.
DB Values = [1,23,33,445,6656,88]
Example values of the CSV files:
File 1 values = [1,23,445,77,66,556,54]
File 2 values = [1,23,45,77,366]
File 3 values = [1,23,5,77,5356,524]
Output needed:
{'1':[(user1, some value),(user2, some value)...]}
Here my code:
def LCR(request):
template = "LCR\LCRGen.html"
dest = Destination.objects.values_list('dest_num', flat=True)
ratelist = { }
csv_file = { }
data_set = { }
io_string = { }
vendor = RateFile.objects.values_list()
v_count = vendor.count()
for v_id, v_name, v_file in vendor:
vendor_name = str(v_name)
vendornames = str(v_name)
vendornames = { }
for desNum in dest:
desNum = str(desNum)
for countvar in range(v_count):
csv_file[vendor_name] = RateFile.objects.get(id=v_id).ven_file
data_set[vendor_name] = csv_file[vendor_name].read().decode("UTF-8")
io_string[vendor_name] = io.StringIO(data_set[vendor_name])
next(io_string[vendor_name])
for column in csv.reader(io_string[vendor_name], delimiter=str(u",")):
vendornames[column[0]] = column[1]
for venNum, venValue in vendornames.items():
venlen = len(venNum)
deslen = len(desNum)
if venlen >= deslen or venlen <= deslen:
if desNum[:-1] == venNum[:-1] and desNum[:-2] == venNum[:-2] and desNum[:-3] == venNum[:-3]:
ratelist[desNum] = [(vendor_name, venValue),]
if (vendor_name, venValue) in ratelist[desNum]:
ratelist[desNum] = [
(vendor_name, venValue),]
elif desNum[:-1] == venNum[:-2] and desNum[:-2] == venNum[:-3] and desNum[:-3] == venNum[:-4]:
ratelist[desNum] = [(vendor_name, venValue),]
if (vendor_name, venValue) in ratelist[desNum]:
ratelist[desNum] = [
(vendor_name, venValue),]
elif desNum[:-1] == desNum[:-3] and desNum[:-2] == venNum[:-4] and desNum[:-3] == venNum[:-5]:
ratelist[desNum] = [(vendor_name, venValue),]
elif desNum[:-1] == venNum[:-5] and desNum[:-2] == venNum[:-6]:
ratelist[desNum] = [(vendor_name, venValue),]
if (vendor_name, venValue) in ratelist[desNum]:
ratelist[desNum] = [
(vendor_name, venValue),]
else:
pass
print ( ratelist )
return render ( request, template, { "ratelist" : ratelist } )
Output
Zong, Tata are usernames and the float values is their respective value for the key value of the dictionary.
{'12': [('Zong', ' 0.026')], '213': [('Tata', ' 4.150')], '49': [('Tata', ' 0.531')], '30': [('Zong', ' 0.87')], '454': [('Tata', ' 0.531')], '374': [('Zong', ' 0.87')],
This is what you asked for:
### your data example
db = [1,23,33,445,66,556,88]
us1 = [1,23,445,77,66,556,54]
us2 = [1,23,45,77,366]
### create a list of usernames (to use the string name in dictionary)
userlist = [ "us1", "us2" ]
### intialize the dict for results
values_dict = {}
### open the loop on DB values
for value in db :
# open loop on userlist
for user in userlist :
# if value is found in user list of values
if value in eval(user) :
# if values still NOT a key of results dictionary create the key with the tuple list as values
if value not in values_dict :
values_dict.update({ value : [ ( user, value ) ] })
# else just append the tuple (username, value) to the results dictionary for the DB value corresponding key
else :
values_dict[value].append([ ( user, value ) ])
values_dict
### OUTPUT:
{1: [('us1', 1), [('us2', 1)]], 23: [('us1', 23), [('us2', 23)]], 445: [('us1', 445)], 66: [('us1', 66)], 556: [('us1', 556)]}
but it makes no sense cause it simply check if a value is in the user list of values and add a tuple just to confirm it, it doesn't require all this code, could be simplified a lot. But I'm thinking that I misunderstood your question (please review the english), probably you need to use the DB value as the key to retrieve another value from the user...please review and update

Incomprehensible error with three print following

I have a dictionary defined as follows:
SN = {}
SN[0] = {'verb' : 1 }
In my function I make 3 prints as follows:
print graph
print state
print graph[state]
(I do nothing else with these variables) and it returns:
SN
0
S
How is this possible? Why doesn't it return
SN
0
{'verb' : 1}
The whole code :
abstraction= {}
abstraction['de'] = ['déterminant']
abstraction['le'] = ['déterminant']
abstraction['un'] = ['déterminant']
abstraction['beau'] = ['adjectif', 'substantif']
abstraction['dodu'] = ['adjectif', 'substantif']
abstraction['grand'] = ['adjectif', 'substantif']
abstraction['méchant'] = ['adjectif', 'substantif']
abstraction['noirs'] = ['adjectif', 'substantif']
abstraction['petit'] = ['adjectif', 'substantif']
abstraction['desseins'] = ['substantif']
abstraction['loup'] = ['substantif']
abstraction['poulet'] = ['substantif']
abstraction['gosse'] = ["n'importe quoi"]
abstraction['mange'] = ['verbe']
abstraction['dort'] = ['verbe']
SN = {}
SN[0] = {'déterminant' : 1 }
SN[1] = {'adjectif' : 1, 'substantif' : 2 }
SN[2] = {'adjectif' : 3, '' : 'ok' }
SN[3] = {'' : 'ok' }
SV = {}
SV[0] = {'verbe' : 1}
SV[1] = {'transitions' : 'SN', '' : 'ok'}
SV[2] = {'' : 'ok'}
def transitions(data, graph, state = 0, transit = []) :
print 'data avt if data :'
print data
if data :
if 'transitions' in graph[state] :
return transitions(data, graph[state]['transitions'], 0, transit)
symbol = data[0]
if symbol not in abstraction.keys() :
return ['impossible, un des mots n\'est pas reconnu par l\'automate']
for a in abstraction[symbol] : # loop on abstractions
print graph
print state
print graph[state]
if a in graph[state] :
state = graph[state][a]
return transitions(data[1:], graph, state, transit + [a])
else :
return transit + [symbol] + ['impossible']
else :
if '' in graph[state] :
return transit + [graph[state]['']]
else : return transit + ['impossible']
I think your problem here is that graph == "SN", rather than (as you apparently expect) graph == SN.
To put it another way, graph is referencing a str object with value "SN", not the dict object also referenced by the name SN.
Therefore graph[0] is the first character in the string "SN", which is the letter "S".
In the case graph == SN, the output from
print graph
print state
print graph[state]
would be:
{0: {'verb': 1}} # note: not 'SN'
0
{'verb': 1}
Edit:
Now that you've posted your code, this section:
SN = {}
SN[0] = {'déterminant' : 1 }
SN[1] = {'adjectif' : 1, 'substantif' : 2 }
SN[2] = {'adjectif' : 3, '' : 'ok' }
SN[3] = {'' : 'ok' }
creates a dictionary
SN = {0: {'déterminant': 1}, 1: {'adjectif': 1, 'substantif': 2},
2: {'adjectif': 3, '': 'ok'}, 3: {'': 'ok'}}
However, in the next part:
SV[1] = {'transitions' : 'SN', '' : 'ok'}
you assign the string 'SN' to the key 'transitions', not the actual dictionary SN. That should have been:
SV[1] = {'transitions': SN, '': 'ok'}
# ^ no quote marks
Also, as all of your keys are integers starting from zero, you could consider using a list instead of a dictionary, e.g.:
SN = []
SN.append({'déterminant': 1})
SN.append({'adjectif': 1, 'substantif': 2})
...

Categories