Python - Lists checking if something has been randomised already - python

Okay, so I am creating a program in python and basically it is a troubleshooting program for mobile phone users, it's very basic as of now, and I am in the situation where I am creating a list for the questions to be asked.
I will use the random module to randomise a string from the troubleshooting questions list, but I don't want it to randomise the first question in the list, then the first question in the list again.
So the real question; how do I check if the randomised string has already been randomised and if it has I want my program to randomise another string from the list, and if it has already been said then randomise another, if not use that string, etcetera.
Note: This program is no where near complete, I literally just started this now, so I am calling the function at the end so I can run the program at different times to see if it works.
import random
Questions = [
'Has your phone gotten wet?', 'Have you damaged your screen?', 'Is the phone at full battery?',
'Has your phone been dropped?', ' Does the mobile phone turn itself off?', 'Does the device keep crashing',
'Does the phone keep freezing?', 'Can you not access the internet on your phone?', 'Is the battery draining quickly?',
'Can you not access certain files on your phone?'
]
Solutions = [
'Put your mobile phone inside of a fridge, it sounds stupid but it should work!', 'Try turning your device on and off',
'Visit your local mobile phone store and seek help'
]
def PhoneTroubleshooting():
print('Hello, welcome to the troubleshooting help section for your mobile phone.\n'
'This troubleshooting program is going to ask you a series of questions, to determine the issue with your device.')
answer = print(random.choice(Questions))
if answer == 'yes':
print('Okay, I have a solution', random.choice(Solutions))
else: print('Okay, next problem')
PhoneTroubleshooting()

Instead of choosing a single random element at a time, you should randomize the entire list using shuffle, then iterate over that. i.e.
random.shuffle(Questions) # This shuffles `Questions` in-place
print(Questions[0])
...
Note, however, that you likely want to keep both of your lists coordinated -- i.e. you still want your answers to match your questions, so you should randomize the indices instead of the values:
inds = range(len(Questions))
random.shuffle(inds)
print(Questions[inds[0]])
...
print(Answers[inds[0]])

Related

Building a ranking list in Python: how to assign scores to contestants?

(I posted this on the wrong section of Stackexchange before, sorry)
I'm working on a assignment which is way above my head. I've tried for days on end figuring out how to do this, but I just can't get it right...
I have to make a ranking list in which I can enter a user, alter the users score, register if he/she payed and display all users in sequence of who has the most score.
The first part I got to work with CSV, I've put only the basic part in here to save space. The menu and import csv have been done: (I had to translate a lot from my native language, sorry if there is a mistake, I know it's a bad habit).
more = True
while more:
print("-" * 40)
firstname = raw_input("What is the first name of the user?: ")
with open("user.txt", "a") as scoreFile:
scoreWrite = csv.writer(scoreFile)
scoreWrite.writerow([firstname, "0", "no"])
scoreFile.close()
mr_dnr = raw_input("Need to enter more people? If so, enter 'yes' \n")
more = mr_dnr in "yes \n"
This way I can enter the name. Now I need a second part (other option in the menu of course) to:
let the user enter the name of the person
after that enter the (new) score of that person.
So it needs to alter the second value in any entry in the csv file ("0") to something the user enters without erasing the name already in the csv file.
Is this even possible? A kind user suggested using SQlite3, but this basic CSV stuff is already stretching it far over my capabilities...
Your friend is right that SQlite3 would be a much better approach to this. If this is stretching your knowledge too far, I suggest having a directory called users and having one file per user. Use JSON (or pickle) to write the user information and overwrite the entire file each time you need to update it.

Taking an input and searching for a key word

i am trying to create a program which is a computer diagnostic service. I want to be able to ask the user what their problem is then extract key words from it. Then I want to print a solution. For example, the user says "My screen is broken", the program recognises "screen" and prints the solution for a broken screen. I honestly have no idea how to do this and i really need some help. Thanks!
with some dictionary of keywords to solutions d,
d = {'screen': 'Get a new screen', ...}
problem = input('What did you do? ').lower()
for k in d:
if k in problem:
print(d[k])
For each keyword, check if it's in the problem. If it is, print the associated solution
This works too
import re
D = {'screen': 1, 'keyboard': 2, 'mouse': 3}
keywords = set(D)
wordre = re.compile(r'\w+')
problem = "The cursor doesn't move on the screen when I move the mouse"
found = set(wordre.findall(problem.lower())) & keywords
print(found) # prints {'mouse', 'screen'}
Your question doesn't specify if your code will impose any limitations with regards to the extent of the user's input.
Assuming that the user will be able to describe his problem to a great extent (i.e input raw text as opposed to just typing a sentence or two) you can use the summa module.
If you take a look at its documentation, you will see that by applying its keywords function on any text; you can extract keywords out of it. Consequently, you can parse those arguments to print the respective solutions. A simple way to do this is to maintain a dictionary with your keywords of interest as keys and their solutions as values; and then just simply cross-check the summa generated keywords against these to print your final solution.

Python checking users input

So, basically, this is my code:
import random
import os
answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.')
print('The program has detected that you have entered a query regarding: '
if 'wet' or 'water' or 'liquid' or 'mobile' in answer:
print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!')
What I want to know is, say for example if the user enters the keywords 'wet' and 'mobile' as their input, how do I feed back to them knowing that my program has recognised their query.
So by saying something like 'The program has detected that you have entered a query regarding:' how do I filter their keywords into this sentence, say, if they entered 'My mobile phone has gotten wet recently', I want to pick out 'mobile' and 'wet' without saying:
print('The program has detected that you have entered wet')
Because that sounds stupid IMO.
Thanks
If I understand your question correctly, this should solve your problem. Just put the print statement inside the if condition! Very simple, I guess :)
import random
import os
answer = input('What is the problem with your mobile phone? Please do not enter more than one sentence.')
if 'wet' or 'water' or 'liquid' or 'mobile' in answer:
print('The program has detected that you have entered a query regarding: water') # or anything else wet or whatever
print('Put your mobile phone inside of a fridge, it sounds stupid but it should work!')
You can do that with a tuple, a list and any function:
SEND_REPORT_TUPLE = ('wet', 'water', 'liquid', 'mobile')
#make a list from the input
input_list = answer.split(" ")
#And then the use any function with comprehension list
if any(e in SEND_REPORT_TUPLE for e in input_list):
print("The program has detected a query...")

Checking for specific output from Python's DNS Resolver Query

I'm trying to write something that will ask users to input a specific domain (say, Google.com), and if _spf.google.com is in the SPF TXT record for Google.com, I want it to say "Yup". If not, I want it to say "Nope." Right now, the code will ask me for the domain, and it'll look up the SPF record, but I can't get it to say "yup." Why not? I've tried turning it into a string, but even that wouldn't get me what I wanted. What am I doing wrong here?
To add to that, what would you guys recommend is a good jumping off point for figuring out what code I'd need to write to figure out how many DNS lookups an SPF record is ultimately using?
import dns.resolver
question= raw_input("What domain do you want? ")
def PrintandGoogle(question):
answer=dns.resolver.query(question,"TXT")
for data in answer:
print data
if "_spf.google.com" in answer:
print "Yup."
else:
print "Nope."
printAndGoogle(question)
If your if is inside your loop:
if "_spf.google.com" in data.to_text():
If your if is outside your loop:
if any("_spf.google.com" in data.to_text() for data in answer):

How can I parse email text for components like <salutation><body><signature><reply text> etc?

I'm writing an application that analyzes emails and it would save me a bunch of time if I could use a python library that would parse email text down into named components like <salutation><body><signature><reply text> etc.
For example, the following text "Hi Dave,\nLets meet up this Tuesday\nCheers, Tom\n\nOn Sunday, 15 May 2011 at 5:02 PM, Dave Trindall wrote: Hey Tom,\nHow about we get together ..." would be parsed as
Salutation: "Hi Dave,\n"
Body: "Lets meet up this Tuesday\n"
Signature: "Cheers, Tom\n\n"
Reply Text: "On Sunday, 15 May 2011 at 5:02 PM, Dave Trindal wrote: ..."
I know there's no perfect solution for this kind of problem, but even a library that does good approximation would help. Where can I find one?
https://github.com/Trindaz/EFZP
This provides functionality posed in the original question, plus fair recognition of email zones as they commonly appear in email written by native English speakers from common email clients like Outlook and Gmail.
If you score each line based on the types of words it contains you may get a fairly good indication.
E.G. A line with greeting words near the start is the salutation (also salutations may have phrases that refer to the past tense e.g. it was good to see you last time)
A Body will typically contain words such as "movie, concert" etc. It will also contain verbs (go to, run, walk, etc) and questions marks and offerings (e.g. want to, can we, should we, prefer..).
Check out http://nodebox.net/code/index.php/Linguistics#verb_conjugation
http://ogden.basic-english.org/
http://osteele.com/projects/pywordnet/
the signature will contain closing words.
If you find a datasource that has messages of the structure you want you could do some frequency analysis to see how often each word occurs in each section.
Each word would get a score [salutation score, body score, signature score,..]
e.g. hello could occur 900 times in the salutation, 10 times in the body, and 3 times in the signature.
this means hello would get assigned [900, 10, 3, ..]
cheers might get assigned [10,3,100,..]
now you will have a large list of about 500,000 words.
words that don't have a large range aren't useful.
e.g. catch might have [100,101,80..] = range of 21
(it was good to catch up, wanna go catch a fish, catch you later). catch can occur anywhere.
Now you can reduce the number of words down to about 10,000
now for each line, give the line a score also of the form [salutation score, body score, signature score,..]
this score is calculated by adding the vector scores of each word.
e.g. a sentence "hello cheers for giving me your number" could be:
[900, 10, 3, ..] + [10,3,100,..] + .. + .. + = [900+10+..,10+3+..,3+100,..]
=[1023,900,500,..] say
then because the biggest number is at the start in the salutation score position, this sentence is a salutation.
then if you had to score one of your lines to see what component the line should be in, for each word you would add on its score
Good luck, there is always a trade-off between computation complexity and accuracy. If you can find a good set of words and make a good model to base you calculations it will help.
The first approach that comes to mind (not necessarily the best...) would be to start off by using split. here's a little bit of code and stuff
linearray=emailtext.split('\n')
now you have an array of strings, each one like a paragraph or whatever
so linearray[0] would contain the salutation
deciding where the reply text starts is a little more tricky, i noticed that there is a double newline just before it so maybe do a search for that from the back and hope that the last one indicates the start of the reply text.
Or store some signature words you might expect and search for those from the front, like cheers, regards, and whatever else.
Once you figure out where the signature is the rest is the rest is easy
hope this helped
I built a pretty cheap API for this actually to parse the contact data from signatures of emails and email chains. It's called SigParser. You can see the Swagger docs here for it.
Basically you send it a header 'x-api-key' with a JSON body like so and it parses all the contacts in the reply chain of an email.
{
"subject": "Thanks for meeting...",
"from_address": "bgates#example.com",
"from_name": "Bill Gates",
"htmlbody": "<div>Hi, good seeing you the other day.</div><div>--</div><div>Bill Gates</div><div>Cell 777-444-8888</div>LinkedInTwitter",
"plainbody": "Hi, good seeing you the other day. \r\n--\r\nBill Gates\r\nCell 777-444-8888",
"date": "Mon, 28 May 2018 23:33:40 +0000 (UTC)"
}

Categories

Resources