Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am writing software in Python that needs to do the following:
Assign values to variables by getting input from the user
Choose the next question to ask the user based on their previous answer
Take action based on the variables once all questions have been asked
I saw an example on here which set questions in a Python dictionary, and that included what question to jump to based on the answer entered. This was very neat and easy to follow, so I started implementing that. I was then going to follow this by comparing the variables to a second dictionary which would then determine what action to take - a decision matrix I believe this is called.
I came to a grinding halt, however, on a question that asks for the date. I have no idea how to check the date is in the right format, and how to get Python to check a valid date has been entered and, if it has, to move to a specific next question. Turns out there is more than one occurrence of this problem.
The code follows below. You can easily see in questions relating to candate and frequency1 and frequency2 where I have come a cropper.
The question, I guess, is whether I can do this using a dictionary to define questions and flow, or whether I will have to suck it up and create a load of IF statements. The only reason I started with dictionaries is to make it easy to implement, maintain and expand. Once I have nailed this, I need to implement much bigger question sets, so would like the question flow to be as elegant and simple as possible.
Apologies for obfuscating the questions.
If you answer, I would just point out this is the first thing I have tried to write in Python beyond asking for someone's name and printing it so simpler is better for me! Thanks!
#Stopquestions is a dictionary containing all the questions that could be asked of the user. It also controls the flow of the questions.
stopquestions = {
'stopconfirm':
{
'prompt':'Do you want to take this action? Y/N ',
'Y':'prev',
'N':'genericerror'
},
'prev':
{
'prompt':'Previously done? Y/N ',
'Y':'bamerch',
'N':'frequency1'
},
'bamerch':
{
'prompt':'Was that with B or M? B/M ',
'B':'candate',
'M':'candate'
},
'candate':
{
'prompt':'What was the date? DD/MM/YYYY ',
'DD/MM/YYYY':'length',
'Anything but the above':'genericerror'
},
'length':
{
'prompt':'Yes or no with reference to length? Y/N ',
'Y':'frequency2',
'N':'frequency2'
},
'frequency1':
{
'prompt':'Choose freq? W/F/M/Q/A ',
'W/F/M/Q/A':'dis',
'Anything but the above':'genericerror'
},
'frequency2':
{
'prompt':'Choose freq? W/F/M/Q/A ',
'W/F/M/Q/A':'end',
'Anything but the above':'genericerror'
},
'dis':
{
'prompt':'Disagreement with recent? Y/N ',
'Y':'end',
'N':'end'
},
'genericerror':
{
'text':'This is a basic example of how we can catch errors.',
'action':'end'
}
}
I would look at the date, and if it does not match the formatting ask the user to reinput the data.
arrow is a great tool to handle this:
import arrow
try:
arrow.get('01/01/2021', 'MM/DD/YYYY')
except arrow.parser.ParserMatchError:
print(False)
https://arrow.readthedocs.io/en/latest/
UPDATE
def check_format(date, fmt='MM/DD/YYYY'):
try:
x = arrow.get(date)
return x.format('MM/DD/YYYY')
except (arrow.parser.ParserMatchError, arrow.parser.ParserError):
if fmt: # 'MM/DD/YYYY'
try:
x = arrow.get(date, fmt)
return x.format('MM/DD/YYYY')
except arrow.parser.ParserMatchError:
return False
return False
print(check_format('2021-01-01')) # 01/01/2021
print(check_format('2021-01-01', 'MM/DD/YYYY')) # 01/01/2021
print(check_format('01/01/2021', 'MM/DD/YYYY')) # 01/01/2021
print(check_format('June was born in May 10 1980', 'MMMM D YYYY'))) # 05/10/1980
print(check_format('01/2021', 'MM/DD/YYYY')) # False
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I'm building a scraping spider and I would like some help on how to extract the right information out of each response in Python
response.css(".print-acta-temp::text").get()
'TEMPORADA 2021-2022'
I would like to know how to collect only the 2021-2022. Should I use the str command?
response.css(".print-acta-data::text").get()
'Data: 14-05-2022, 19:00h'
I need to extract only the date into one variable and the time into another variable.
response.css(".print-acta-comp::text").get()
' CADET PRIMERA DIVISIÓ - GRUP 2'
I need to collect the data before the first space, the data collected between the 2 spaces and finally the number into another variable.
response.css(".print-acta-jornada::text").get()
'Jornada 28'
I need to collect the data after the first space.
if you trust the website to produce the data you want exactly followed by 'TEMPORADA ' all the time you can use
tu_string = 'TEMPORADA 2021-2022'
nueva_string = tu_string.replace('TEMPORADA ','')
print (nueva_string)
like, there's regex and all of that, but you can worry about learning that later, tbh.
I need to collect the data before the first space, the data collected
between the 2 spaces and finally the number into another variable.
a simple way to do this is to split
teva_string = 'CADET PRIMERA DIVISIÓ - GRUP 2'
teva_lista = teva_string.split(' ')
print (teva_lista)
Any decision on how to parse a string is going to depend on one's assumptions about what form the strings are going to take. In the particular case of 'TEMPORADA 2021-2022', doing my_string.split(' ')[1] will get the years. 'Data: 14-05-2022, 19:00h'.split(' ') will get the list ['Data: 14-05-2022,, '19:00h'], while 'Data: 14-05-2022, 19:00h'.split('-') will get ['Data: 14-05-2022', ' 19:00h']. You can also use datetime libraries or regular expressions, with the latter allowing for more customization if the form of your data varies.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a list of users. Each user has First name and Last name fields. Most of user details are accurate. From time to time, I can see users that signed up using fake details.
For example:
Valid: Alon Mask
In valid: Asd Dfds
I'm looking to find a way to check if name is legitim or not. What is the best approach to solve it?
My development stack is Python.
You can use the google cloude infotype API to extrat types of info from a given string
https://cloud.google.com/dlp/docs/quickstart-json
It works by sending a Json request to the API which will return the info you're looking for with minimum likelihood.
Example with phone number:
{
"item":{
"value":"My phone number is (206) 555-0123."
},
"inspectConfig":{
"infoTypes":[
{
"name":"PHONE_NUMBER"
},
{
"name":"US_TOLLFREE_PHONE_NUMBER"
}
],
"minLikelihood":"POSSIBLE",
"limits":{
"maxFindingsPerItem":0
},
"includeQuote":true
}
}
Response:
{
"result":{
"findings":[
{
"quote":"(206) 555-0123",
"infoType":{
"name":"PHONE_NUMBER"
},
"likelihood":"LIKELY",
"location":{
"byteRange":{
"start":"19",
"end":"33"
},
"codepointRange":{
"start":"19",
"end":"33"
}
},
"createTime":"2018-11-30T01:01:30.883Z"
}
]
}
}
https://cloud.google.com/dlp/docs/infotypes-reference#global has all the infotypes, you probably want experiment with those:
PERSON_NAME
A full person name, which can include first names, middle names or initials, and last names. Note: Not recommended for use during latency sensitive operations.
FIRST_NAME
A first name is defined as the first part of a PERSON_NAME. Note: Not recommended for use during latency sensitive operations.
LAST_NAME
A last name is defined as the last part of a PERSON_NAME.
Note: Not recommended for use during latency sensitive operations.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have found help with starting an assignment that I previously did not know how to begin. I currently need to figure out a way to compare several birthdays with the current date, as prompted by the user, with the last day of a month as prompted by the user. I know there is a date timemodule that can tell the current date but I am unsure of how to use the module to work with what the user inputs...if that makes sense.
For example: If the user inputs 11/27/18 as the current date and June as the comparison month (my professor requires a month be entered instead of a date), I need to compare the birthdays from an opened file with 11/27/18 and 06/30/19 and print however many of those dates occur before July 1st, 2019 (it needs to be printed in words, my professor requires specific formatting).
I know how to format the dates that are input in my program, but I am unsure how to compare the dates from the file with what is input for comparison as it could be different every time. Currently what I have now is the inputs of strings where the user would prompt the current date and the month and I have the file opened.
your program would look something like this its not exactly what your criteria is but this is a step in the right direction. This is just one way to do it so someone might have a better program.
FriendList=[" name 1", "name 2"]
PhoneList=[ " 123" , "456"]
Birthday=["January" , "February"]
print(Birthday)
Date=input(" please choose a month or press q to exit")
# in lists the first string or number in each list will be together
# example: if janurary is chosen then name 1 and 123 will appear
while Date != 'q': # runs until q is pressed to quit
for i in range (2):# loop goes through the 2 names in the list
if Birthday[i] == Date: # compares the list of names to the date
print(FriendList[i],"" , Date[i], "" ,PhoneList[i])
Date=input(" please choose a month or press q to exit")
First you need to check the dates, start by figuring out this part: "birthday between the current date and the last day of a month "
Once you have that working, loop through the friends, and if they meet the condition then add them to a new list.
Sort the new list by alphabetical order, and print it.
This should give you an idea of where to start, once you've some code you can post that and ask for help for specific problems, but nobody will do your final for you (that's cheating!)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am having trouble to query my database maybe someone could give me a hand.
I am using a django application so I guess Sqlite3 >> and the output I would like to get is the score value
b = Answer.objects.get(id = 23)
which give me an output of :
<Answer: Answer to questionID '4' : AnswerID '23'>
when I do :
b.values
I get a dict in the form :
['{
"1)Long descriptive text":Score,
"2)Long descriptive text":Score,
"3)Long descriptive text":Score,
"4)Long descriptive text":Score
}']
with score beeing an Integer from 0 to 100 so for example "Long descriptive text":85
I need to extract the score using a query but I can't manage to do it
Normaly for a Dict[key:value] I would do a Dict[key] but here I do not know how to do it
could you give me a hand
Thx you very much
This looks suspiciously like Django If so:
so b = Answer.objects.get(id = 23) is not truely that - what you are seeing is the str function of the Answer when you print it off. because you used .get rather then a .filter you get the object rather then a QuerySet (which you can think of as being a list).
Basically, I suspect you shouldn't be using values, but accessing the data... something like
b = Answer.objects.get(id=..)
b.score
or if you wanted to loop over other answers:
answers = Answer.objects.filter(...)
for a in answers:
a.score
for what the .score is, look in your models.py file - look what parameters is has (things looking like score = models.IntegerField() etc, then you would use a.score)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
mother_dict=
{'son_dict':{'Name':'Jason','Age':26},'daughter_dict':{'Name':'Emma','Age':19}}
father_dict={}
father_dict['Child']=mother_dict[son_dict]
I need a way to replace father_dict['Child'] with a dictionary from mother_dict based on input.
I've tried deleting the contents of father_dict and replacing them with the contents of mother_dict with .update(), but that of course adds the whole dictionary, I've tried using input() to ask the user for a child, so if they said 'Jason' it would replace 'Child' with son_dict, but when I got into families with ten or so kids there would need to be ten functions, and if the children's names changed then both the functions and the dictionaries would need to be re-written. I'm hung up on using input to grab a specific dictionary from mother_dict and copying it to father_dict.
Maybe something like the following?
choice = ''
mother_dict= {'son_dict':{'Name':'Jason','Age':26},'daughter_dict':{'Name':'Emma','Age':19}}
father_dict = {}
while choice not in mother_dict:
choice = raw_input('Which dict do you want? ')
father_dict[choice] = mother_dict[choice]
This code gets input until the input is valid (it is in mother_dict), and then it adds that input to father_dict.