Currently I have my data in a directory
myDict = {'a':'Andy','b':'Bill','c':'Carly' }
I want to achieve something like
input = a --> output = Andy
input = ab --> output = Andy Bill
input = abc --> output = Andy Bill Carly
How can I do that ? Please help me
def girdi_al():
isim = input("isim giriniz: ")
return isim
def isim_donustur(isim):
cikti = isim()
donusum = {'a':'Ankara','b':'Bursa','c':'Ceyhan'}
string = ''
for char in cikti:
string += donusum[char] + ' '
print(string )
def main():
isim_donustur(girdi_al)
# === main ===
main()
Iterate through the individual letters of the input string.
Look up each item in the dictionary.
Concatenate the results as you go.
Can you handle each of those capabilities? If not, please post your best attempt and a description of the problem.
isim is not a function, and all you need to do is access that key in the dictionary
def girdi_al():
isim = input("isim giriniz: ")
return isim
def isim_donustur(isim):
cikti = isim
donusum = {'a':'Ankara','b':'Bursa','c':'Ceyhan'}
#How can I do?
result = []
for letter in cikti:
result.append(donusum[cikti])
print(' '.join(result))
def main():
isim_donustur(girdi_al)
# === main ===
main()
somthing like this
myDict = {'a':'Andy','b':'Bill','c':'Carly' }
input_str = "abc"
" ".join([v for k,v in myDict.items() if k in list(input_str)])
Related
below I have created an emoji converter function in Python, however, it seems to be not working. Can anyone figure out what I'm doing wrong? (Btw I'm relatively new to coding :))
def emoji_convertor(message):
words = message.split(" ")
emojis = {
" :) = 😄",
" :( = 😔"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
message = input("> ")
result = emoji_convertor(message)
print(result)
This is how you create a dictionary.
def emoji_convertor(message):
words = message.split(" ")
emojis = {
":)": "😄",
":(": "😔"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
Or, better:
def emoji_convertor(message):
words = message.split(" ")
emojis = {
":)": "😄",
":(": "😔"
}
output = ' '.join((emojis.get(word, word) for word in words))
return output
I am currently working on a program that takes in user inputs, and depending on that users input the string should change. I was wondering if there was a way I could alter the string once the user input has been received. The following is a sample code.
title = input('Title: ')
subtitle = input('Subtitle: ')
chapter = input('Chapter: ')
subchapter = input('Subchapter: ')
title1 = '/title{}'.format(title)
subtitle1 = '/subtitle{}'.format(subtitle)
chapter1 = '/chapter{}'.format(chapter)
subchapter1 = '/subchapter{}'.format(subchapter)
output_txt = title1+subtitle1+chapter1+subchapter1
print(output_txt)
Input taken by user: Should be a number
The input would then be formatted to its perspective string
Based on the user input the string, output_txt, should be formatted accordingly
Scenario 1:
User Input
Title: 4
Subtitle:
Chapter: 12
Subchapter: 1
output_txt should be
output_txt = '/title4/chapter12/subchapter1'
Scenario 2:
User Input
Title: 9
Subtitle:
Chapter: 2
Subchapter:
output_txt should be
output_txt = '/title9/chapter2'
I have been using if elif but since there could be multiple combinations I do not think doing it that way is the most efficient.
Any help or tips in the right direction is greatly appreciated
You could use an if-else condition while assigning string values to the variable
title = input('Title: ')
subtitle = input('Subtitle: ')
chapter = input('Chapter: ')
subchapter = input('Subchapter: ')
title1 = '/title{}'.format(title) if title else ''
subtitle1 = '/subtitle{}'.format(subtitle) if subtitle else ''
chapter1 = '/chapter{}'.format(chapter) if chapter else ''
subchapter1 = '/subchapter{}'.format(subchapter) if subchapter else ''
output_txt = title1+subtitle1+chapter1+subchapter1
print(output_txt)
Let me introduce you to typer
typer will help you to create a CLI with python easily
for your code can be approached like this
import typer
# By defining the data type, we can set the input only a number
def main(title: int = None, subtitle: int = None, chapter: int = None, subchapter: int = None):
title = f'/title{title}' if title else ''
subtitle = f'/subtitle{subtitle}' if subtitle else ''
chapter = f'/chapter{chapter}' if chapter else ''
subchapter = f'/subchapter{subchapter}' if subchapter else ''
output_txt = title+subtitle+chapter+subchapter
print(output_txt)
if __name__ == "__main__":
typer.run(main)
And you just need to run it by adding the parameter for each one you need
python script_name.py --title 5 --chapter 2 --subchapter 7
Here's an approach that uses a regular expression for input validation and list comprehensions to gather the inputs and build the output string.
import re
def get_input( label: str = None ) -> int:
entry = input(label + ': ')
if re.match(r'^\d+$', entry) is None:
return None
if int(entry) <= 0:
return None
return int(entry)
tpl_labels = ('Title', 'Subtitle', 'Chapter', 'Subchapter')
lst_values = [get_input(x) for x in tpl_labels]
output_txt = '/'.join([f'{x.lower()}{y}' for x, y in zip(tpl_labels, lst_values) if y])
if not output_txt:
print('No valid responses given.')
else:
output_txt = '/' + output_txt
print(output_txt)
The get_input() function expects each value entered by the user to be a positive integer. All other input is silently ignored (and None is returned).
Just for completeness you might want to test for a number as well.
# Test
def test_for_int(testcase):
try:
int(testcase)
return True
except ValueError: # Strings
return False
except TypeError: # None
return False
# Get the inputs
title = input('Title: ')
subtitle = input('Subtitle: ')
chapter = input('Chapter: ')
subchapter = input('Subchapter: ')
# Run the tests and build the string
output_txt = ''
if test_for_int(title):
output_txt += '/title{}'.format(title)
if test_for_int(subtitle):
output_txt += '/subtitle{}'.format(subtitle)
if test_for_int(chapter):
output_txt += '/chapter{}'.format(chapter)
if test_for_int(subchapter):
output_txt += '/subchapter{}'.format(subchapter)
print(output_txt)
You can do something like this...
def get_user_input(message):
user_input = input(message+' : ')
if user_input == '' or user_input.isdigit() == True:
return user_input
else:
return False
def f():
title = ''
while True:
title = get_user_input('title')
if title == False:
continue
else:
break
subtitle = ''
while True:
subtitle = get_user_input('subtitle')
if subtitle == False:
continue
else:
break
chapter = ''
while True:
chapter = get_user_input('chapter')
if chapter == False:
continue
else:
break
subchapter = ''
while True:
subchapter = get_user_input('subchapter')
if subchapter == False:
continue
else:
break
s = ''
s += '/title'+str(title) if title != '' else ''
s += '/subtitle'+str(subtitle) if subtitle != '' else ''
s += '/chapter'+str(chapter) if chapter != '' else ''
s += '/subchapter'+str(subchapter) if subchapter != '' else ''
return s
Output...
title : 1
subtitle : 2
chapter : 3
subchapter : 4
'/title1/subtitle2/chapter3/subchapter4'
title : 1
subtitle :
chapter : 3
subchapter :
'/title1/chapter3'
Obviously you need to add few changes to the code for your specific purpose.
the error is when I enter d, and Enter a sentence: David, y r u l8
David,why\nare\nyou\nlate\n , but I need it to return David, why are you late
def update_dictionary(fileName,dictionary):
try:
a = open(fileName)
except IOError:
print( fileName,"does not exist.")
print("The dictionary has",len(dictionary),"entries.")
return dictionary
with a:
print(fileName,"loaded successfully.")
for word in a:
c,b = word.split(",")
dictionary[c] = b
print("The dictionary has",len(dictionary),"entries.")
return dictionary
def deslang(filename,dic):
x = ""
words = filename.split(" ")
for i in range(len(words)):
if words[i] in dic:
words[i] = dic[words[i]]
for i in range(len(words)-1):
x = x + words[i] + " "
x = x + words[len(words) -1]
return x
def main():
name = {}
while 1:
u_input = input("Would you like to (a)dd words to the dictionary, (d)e-slang a sentence, or (q)uit?: ")
if u_input == "q":
break
if u_input == "a":
fileName = ""
while len(fileName) == 0:
fileName = input("Enter a filename: ")
name = update_dictionary(fileName,name)
if u_input == "d":
sentence = ""
while len(sentence) == 0:
sentence = input("Enter a sentence: ")
print(deslang(sentence, name))
if name =="main":
main()
You need to strip the newlines off each of the dictionary lines. In other words:
for word in a:
c,b = word.rstrip().split(",")
dictionary[c] = b
When you iterate a file like for word in a:, you get a string for each line in the file, including the newline at the end. So, your dictionary ends up full of entries like 'y': 'why\n' instead of 'y': 'why'.
You can strip the trailing newline from word.split(",") by calling str.strip.
word.strip().split(",")
You can also use read() to load the contents of the file which doesn't include newlines.
I want to ask the user for 2 inputs, first name and last name, return a greeting and store the names in a Dictionary with the Keys being 'FName' and 'LName'
The following stores the greeting fine....
def name():
d = {}
x = input('Please enter your first name: ')
y = input('Please enter your last name: ')
d = {}
d[x] = y
print("Hello", x, y)
print(d)
name()
but I am not sure how to get the key/values in the dictionary properly. Right now it stores the equivalent of:
{'Joe': 'Smith'}
I know I need to reformat the following line different I am just not sure how to approach it...
d[x] = y
You'll want to manually set the keys you are storing against
d['FName'] = x
d['LName'] = y
Or more simply
d = {
'FName': x,
'LName': y
}
Here is another example:
def name():
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
return d
name()
Nevermind, I figured it out. Sorry.
d['Fname'] = x
d['Lname'] = y
Its a pretty simple operation, but i cant make it work. I know there are plenty of other ways to do this and i have a working code at the moment. But since this is school related, and the teacher asks specifically for str.find i have to make it work his way.
My code at the moment:
def initialer(name):
forname =[0]
space = name.find(" ")
surname = ???
return initialer
print initialer("Andy Olsen")
My working code, but not accepted for this assignment:
def initialer(name):
x = name.split(" ")
y = [words[0] for words in x]
return ".".join(y) + "."
Any suggestions?
my_str = "hello world!"
print my_str[my_str.find(" ") + 1]
Only two words:
def initialer(name):
space_pos = name.find(' ')
if space_pos == -1:
return name[0]
else:
return name[0] + name[space_pos + 1]
Multiple words:
def initialer(name):
space_pos = name.find(' ')
if space_pos == -1:
return name[0]
else:
return name[0] + initialer(name[space_pos + 1:])
More pythonic:
def initialer(name, splitter=' '):
words = name.split(splitter)
return u''.join(zip(*words)[0])