I recently just asked a question on SO regarding on how to turn a text file into a dictionary on Python, it worked until I made a slight adjustment to the code as I want to compare the key to a word in a string, and if the key was the same as the word, it would print the corresponding value, however no output is printed, why is this?
def answerInput():
print("Hello, how may I help you with your mobile device")
a = input("Please enter your query below\n")
return a
def solution(answer):
string = answer
my_dict = {}
with open("Dictionary.txt") as f:
for line in f:
key, value = line.strip("\n").split(maxsplit=1)
my_dict[key] = value
for word in string.split():
if word == my_dict[key]:
print(value)
process = 0
answer = answerInput()
solution(answer)
If anyone it helps, my text file is as goes:
battery Have you tried charging your phone? You may need to replace your battery.
dead Have you tried charging your phone? You may need to replace your battery.
sound Your volume may be on 0 or your speakers may be broken, try using earphones.
screen Your screen may be dead, you may need a replacement.
touchID You may need to wipe the fingerprint scanner, try again.
microphone You may need to replace your microphone.
Read the file into my_dict dictionary first, then do lookups into it (your current code as posted reads the file as it does the lookups). Also, compare the words of the user's answer to the keys, not values of the my_dict dictionary (as your code does).
All of this also means that the code should have 3 parts, perhaps something similar to the solution below.
def read_dictionary(in_file):
my_dict = {}
with open(in_file) as f:
for line in f:
key, value = line.strip('\n').split(maxsplit=1)
my_dict[key] = value
return my_dict
def read_query():
print('Hello, how may I help you with your mobile device')
return input('Please enter your query below\n').strip('\n')
def solve(query, my_dict):
for word in query.split():
if word in my_dict:
print(my_dict[word])
return
return
my_dict = read_dictionary('Dictionary.txt')
query = read_query()
solve(query, my_dict)
you're trying to compare the variable 'answer' to the variable 'key', not the value stored in my_dict[key].
also, I'd suggest you use .lower() such as: if answer.lower() == key
so you'd be able to process user responses even if they are in upper case letters
I'm not sure if this is the way you want it to work and configparser usage is a little different but I kinda like the way it can work here.
import configparser
config = configparser.ConfigParser()
config.read("conf.ini", encoding="utf-8")
def answerInput():
print("Hello, how may I help you with your mobile device")
a = input("Please enter your query below\n")
return a
answer = answerInput()
print(config.get("Answers", answer))
conf.ini file in the same directory:
[Answers]
battery = Have you tried charging your phone? You may need to replace your battery.
dead = Have you tried charging your phone? You may need to replace your battery.
sound = Your volume may be on 0 or your speakers may be broken, try using earphones.
screen = Your screen may be dead, you may need a replacement.
touchID = You may need to wipe the fingerprint scanner, try again.
microphone = You may need to replace your microphone.
This is obviously depending if you already have a huge list of those key value pairs or you are gonna be creating ones. If you are creating ones, this might be a nice strucured way to do it.
Related
Hi all First time having to look for assistance but i am sort of at a brick wall for now. i have been learning python since August and i have been giving a challenge to complete for the end of Novemeber and i hope that there could be some help in making my code works. My task requires to find an ip address which occurs most frequent and count the number of times it appears also this information must be displayed to the user i have been giving 4 files .txt that have the ips. I am also required to make use of non trivial data structures and built in python sorting and/or searching functionalities, make use of functions, parameter passing and return values in the program. Below is a sample data structure they have recommended that i use: -
`enter code here`
def analyse_logs(parameter):
# Your Code Hear
return something
def extract_ip(parameter):
# Your Code Hear
return something
def find_most_frequent(parameter):
# Your Code Hear
return something
# Test Program
def main():
# Your Code Hear
# Call Test Program
main()
And below hear is what i have came up with and the code is completley differant from the sample that has been provided but what i have done dosnt give me output straight back instead creats a new text file which has been sorted but now what i am looking for: -
enter code here
def sorting(filename):
infile = open(filename)
ip_addr = []
for line in infile:
temp = line.split()
for i in temp:
ip_addr.append(i)
infile.close()
ip_addr.sort()
outfile = open("result.txt", "w")
for i in ip_addr:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample_log_1.txt")e here
The code that i have created has sorted everything thats in the .txt file and outputs the most frequent that has been used all the way to the lest frequent. All i am look for is for an algorithim that can sort through the .txt file, find the IP address thats more frequent then print that ip out and how many times it appears. I hope i have provided everything and i am sure this is probally somthing very basic but i just cant get my head round it.
You should keep the number of times the IP addresses are repeated in a variable. You can use dictionary.
ip_count_dict = {"IP1": repeat_count, "IP2": repeat_count}
When first time you find a IP in your list set repeat_count 1 and after that if you find same ip again just increase counter.
For example,
ip_count_dict = {}
ip_list = ['1.1.1.1','1.1.1.2','1.1.1.3','1.1.1.1']
#Loop and count ips
#Final version of ip_count_dict {'1.1.1.1':2 , '1.1.1.2':1, '1.1.1.3':1}
With this dictionary you can store all ips and sort by their value.
P.S.: Dictionary keeps key,value pairs you can search "sort dictionary by value" after all counting thing done.
I am seeking some advice whether it be in terms of a script (possibly python?) that I could use to do the following.
I basically have two documents, taken from a DB:
document one contains :
hash / related username.
example:
fb4aa888c283428482370 username1
fb4aa888c283328862370 username2
fb4aa888c283422482370 username3
fb4aa885djsjsfjsdf370 username4
fb4aa888c283466662370 username5
document two contains:
hash : plaintext
example:
fb4aa888c283428482370:plaintext
fb4aa888c283328862370:plaintext2
fb4aa888c283422482370:plaintext4
fb4aa885djsjsfjsdf370:plaintextetc
fb4aa888c283466662370:plaintextetc
can anyone think of an easy way for me to match up the hashes in document two with the relevant username from document one into a new document (say document three) and add the plain so it would look like the following...
Hash : Relevant Username : plaintext
This would save me a lot of time having to cross reference two files, find the relevant hash manually and the user it belongs to.
I've never actually used python before, so some examples would be great!
Thanks in advance
I don't have any code for you but a very basic way to do this would be to whip up a script that does the following:
Read the first doc into a dictionary with the hashes as keys.
Read the second doc into a dictionary with the hashes as keys.
Iterate through both dictionaries, by key, in the same loop, writing out the info you want into the third doc.
You didn't really specify how you wanted the output, but this should get you close enough to modify to your liking. There are guys out there good enough to shorten this into a fey lines of code - but I think the readability of keeping it long may be helpful to you just getting started.
Btw, I would probably avoid this altogether and to the join in SQL before creating the file -- but that wasn't really your question : )
usernames = dict()
plaintext = dict()
result = dict()
with open('username.txt') as un:
for line in un:
arry = line.split() #Turns the line into an array of two parts
hash, user = arry[0], arry[1]
usernames[hash] = user.rsplit()[0] # add to dictionary
with open('plaintext.txt') as un:
for line in un:
arry = line.split(':')
hash, txt = arry[0], arry[1]
plaintext[hash] = txt.rsplit()[0]
for key, val in usernames.items():
hash = key
txt = plaintext[hash]
result[val] = txt
with open("dict.txt", "w") as w:
for name, txt in result.items():
w.write('{0} = {1}\n'.format(name, txt))
print(usernames) #{'fb4aa888c283466662370': 'username5', 'fb4aa888c283422482370': 'username3' ...................
print(plaintext) #{'fb4aa888c283466662370': 'plaintextetc', 'fb4aa888c283422482370': 'plaintext4' ................
print(result) #{'username1': 'plaintext', 'username3': 'plaintext4', .....................
I have a code that allows me to identify keywords inputted from a user and the system displays the problem the keyword linked to and asks if it is correct. If the user inputs yes a solution is given
# The following is a database of problems, keywords, and solutions.
PROBLEMS = (('My phone does not turn on.',
{'power', 'turn', 'on', 'off'},
('put it on charger.',))
# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', 'correct')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', 'incorrect')))
def main():
"""Find out what problem is being experienced and provide a solution."""
description = input('Welcome to the repair centre. Please state the problem with your device: ')
words = {''.join(filter(str.isalpha, word))
for word in description.lower().split()}
for problem, keywords, steps in PROBLEMS:
if words & keywords:
print('This may be what you are experiencing:')
print(problem)
if get_response('Does this match your problem? '):
print('Please follow the solution given')
for number, step in enumerate(steps, 1):
print('{}. {}'.format(number, step))
print('Once you have carried out the solution suggested by the system the problem with your device should be fixed .')
print('If you have carried out the solution suggested by the system and the problem is not fixed, please take the device to either the manufacturer or to the repair shop to get it fixed professionally.')
break
else:
print('Unfortunately the repair centre cannot help you with your problem.')
def get_response(query):
"""Ask the user yes/no style questions and return the results."""
while True:
answer = input(query).casefold()
if answer:
if any(option.startswith(answer) for option in POSITIVE):
return True
if any(option.startswith(answer) for option in NEGATIVE):
return False
print('Please respond with the positive or negative answer listed : yes, true, correct, no, false, incorrect.')
if __name__ == '__main__':
main()
However how can i store all the solutions in a text file and make the keywords stored in python link to it depending on the user input.
I want a specific line from the text file to be outputted to the user.
Help will be appreciated
We're going to store the keywords and solutions in a csv file. The first entry on each line will be the solution, and all the others will be keywords that direct to this solution.
from collections import defaultdict
import csv
sol_dict = defaultdict(set)
with open('solutions.csv', newline='') as f:
r = csv.reader(f, quotechar='|')
for solution, *keywords in r:
for keyword in keywords:
sol_dict['keyword'].add(solution)
So now we have this dictionary, sol_dict. We can query a keyword sol_dict['power'] and you get back a set of strings, each a solution. (When you make the csv, if you want commas in the solution, you can wrap it in the quotechar, |).
Then walking through the solutions would look something like
problem = input('What is your problem?')
for solution in set.union(*(sol_dict[word] for word in problem.split())):
# Whatever you want to do with solutions
print(solution)
I am a Python 2.7 (and programming) beginner. Also, this is my first question on SO.
I am currently building a little shopping cart application. I am storing shopping cart values in a txt file. If the user running the script has already a cart saved in the txt file from a previous session, I want the program to make the offer to continue with those items in cart.
Here is what I have so far:
my_file = open("cart.txt", "r")
match = re.findall(r'%s' % enter_name, my_file.read())
my_file.close()
#using a regular expression here to find the person's cart by name
#in cart.txt.
if match:
print "Hello %s, welcome back." % enter_name
print "Do you want to use your previous Shopping Cart?"
continue_cart = raw_input("Type 'yes' or 'no' ")
if continue_cart == "yes":
with open("cart.txt", "r") as my_file:
for line in my_file:
line_list = line.split()
print line_list
#to be continued
The final print statement is basically only a placeholder and a way for me to see what the happens. I am kinda stuck there. The code with the for loop at the end basically produces various lines with a list each. Like this
['Martin']
['Milk', '2']
['Apple', '4']
What I want to do is to "access" the values representing products & quantity in order to then add them to the shopping card class. But how to process this list in order to be able to access the values?
Any help is appreciated. Thanks.
As e4c5 said by not utilizing more advanced concepts (a database, or just using a simple json or pickle) you are making it much harder for yourself.
If you want to use only plain text files directly to store and load values not only it's much harder to write the code (honestly, i've been programming for years and I still would not be confident I got that right!) but also for everyone (including yourself in the future) to read the code. And maintainability is really - from experience - the holly grail of programming. That's why we use python after all!
That said, I understand, you are not trying not build a perfect solution but to learn programming!
That said, your cart.txt probably looks something like this:
Martin
Milk 2
Apple 4
Eva
Milk 1
Then your for loop would look like this (for example, but as I said, this is not a right approach and I it is very fragile and buggy!):
enter_name_found = False
cart_items = {}
for line in my_file:
line_list = line.split()
if len(line_list) == 1:
if line_list[0] == enter_name:
enter_name_found = True
else:
if enter_name_found:
break
else:
if enter_name_found:
cart_items[line_list[0]] = line_list[1]
print(cart_items)
EDIT:
To demonstrate how much simpler this all is using a database:
Here is a full example to save a cart:
import shelve
cart = shelve.open("cart.dat")
cart["Martin"] = {"Apple": 5, "Milk": 2}
cart["Eva"] = {"Milk": 1, "Cat": 4}
cart.close()
And full example to load the cart from the DB:
import shelve
cart = shelve.open("cart.dat")
print(cart["Martin"])
print(cart["Eva"])
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.