Why don't these variables output their values properly? - python

I am currently working in Python 3.5 and I'm having an issue with the variables in my dictionary. I have numbers 1-29 as keys, with letters as their pairs and for some reason none of the double digit numbers register as one number. For example, 11 would come out as 1 and 1 (F and F) instead of 11(I) or 13 as one and 3 (F and TH) instead of 13(EO). Is there a way to fix this so that I can get the values of the double digit numbers?
my code is here:
Dict = {'1':'F ', '2':'U ', '3':'TH ', '4':'O ', '5':'R ', '6':'CoK ', '7':'G ', '8':'W ', '9':'H ',
'10':'N ', '11':'I ', '12':'J ', '13':'EO ', '14':'P ', '15':'X ', '16':'SoZ ', '17':'T ',
'18':'B ', '19':'E ', '20':'M ', '21':'L ', '22':'NGING ',
'23':'OE ' , '24':'D ', '25':'A ', '26':'AE ', '27':'Y ', '28':'IAoIO ', '29':'EA '}
textIn = ' '
#I'm also not sure why this doesn't work to quit out
while textIn != 'Q':
textIn = input('Type in a sentence ("Q" to quit)\n>')
textOut = ''
for i in textIn:
if i in Dict:
textOut += Dict[i]
else:
print("Not here")
print(textOut)

Your for i in textIn: will loop over the individual characters in your input. So if you write 11, it will actually be a string '11', and for i in '11' will go over the '1''s separately:
>>> text = input()
13
>>> text
'13' # See, it's a string with the single-quote marks around it!
>>> for i in text:
... print(i)
...
1
3
>>> # As you see, it printed them separately.
You don't need the for loop at all, you can just use:
if textIn in Dict:
textOut += Dict[textIn]
Since your dict has the key '11', and your textIn is equal to '11'.
There is an other major issue in your code too; the textOut variable gets overwritten on every loop, so you lose everything you've done. You want to create it outside of the while loop:
textOut = ''
while textIn != 'Q':
textIn = input('Type in a sentence ("Q" to quit)\n>')
if textIn in Dict:
textOut += Dict[textIn]
else:
print("Not here")
print(textOut)

Related

Pythonic way to print data this data with headers

I have this dataset:
[('Stuff', ' ')
('Available in several colors.', ' ')
('A fits B by Sometimes.', ' ')
('handle $148', 'A ')
('handle base $23', 'A ')
('mirror base $24', 'A ')
(' handle $31', 'B ')
('handle base, $23', 'B ')
('Mirror $24', 'B ')
]
What I need to do is print this data with a "header" based off the second item in the list. Only printing the header when it changes. In this sample, the only 3 options are " ", "A ", and "B ". But in my actual data set there could be 100+ different options, so hard coding them in is not really an options.
I want the printed data to look like this (skipping the " ")
Stuff.
Available in several colors.
A fits B by Sometimes.
A ----------------------
handle $148
handle base $23
mirror base $24
B ----------------------
handle $31
handle base, $23
Mirror $24
the only way to do this I can think of is to hard code the values in, but with 100+ possibilities this would take forever. There must be a better way.
a_printed = False
b_printed = False
for item in list1:
if item[1] == ' ':
print(item[0])
elif item[1] == 'A ':
if a_printed != True:
print('A --------------')
a_printed = True
print(item[0])
elif item[1] == 'B ':
if b_printed != True:
print('B --------------')
b_printed = True
print(item[0])
Any help is appreciated.
You don't need to hard-code the header values, just set a variable to the header and test if the new header is different.
last_header = ' '
for value, header in list1:
if header != last_header:
print(header, '--------------')
last_header = header
print value

Splitting Strings within an Array

I am writing a program in python that reads in a text file and executes any python commands within it. The commands may be out of order, but each command has a letter ID such as {% (c) print x %}
I've been able to sort all the commands with in the document into an array, in the correct order. My question is, how to i remove the (c), so i can run exec(statement) on the string?
Here is the full example array
[' (a) import random ', ' (b) x = random.randint(1,6) ', ' (c) print x ', ' (d) print 2*x ']
Also, I am very new to python, my first assignment with it.
You can remove the index part, by using substring:
for cmd in arr:
exec(cmd[5:])
Take everything right to the parenthesis and exec:
for cmd in arr:
exec(cmd.split(") ")[-1])
Stripping the command-id prefixes is a good job for a regular expression:
>>> import re
>>> commands = [' (a) import random ', ' (b) x = random.randint(1,6) ', ' (c) print x ', ' (d) print 2*x ']
>>> [re.search(r'.*?\)\s*(.*)', command).group(1) for command in commands]
['import random ', 'x = random.randint(1,6) ', 'print x ', 'print 2*x ']
The meaning of regex components are:
.*?\) means "Get the shortest group of any characters that ends with a closing-parentheses."
\s* means "Zero or more space characters."
(.*) means "Collect all the remaining characters into group(1)."
How this explanation makes it all clear :-)
Since the pattern looks simple and consistent, you could use regex.
This also allows for both (a) and (abc123) as valid IDs.
import re
lines = [
' (a) import random ',
' (b) x = random.randint(1,6) ',
' (c) print x ',
' (d) print 2*x '
]
for line in lines:
print(re.sub(r"^[ \t]+(\(\w+\))", "", line))
Which would output:
import random
x = random.randint(1,6)
print x
print 2*x
If you really only want to match a single letter, then replace \w+ with [a-zA-Z].
You may use a simple regex to omit the first alpha character in braces as:
import re
lst = [' (a) import random ', ' (b) x = random.randint(1,6) ', ' (c) print x ', ' (d) print 2*x ']
for ele in lst:
print re.sub("^ \([a-z]\)", "", ele)

Going character by character in a string and swapping whitespaces with python

Okay so I have to switch ' ' to *s. I came up with the following
def characterSwitch(ch,ca1,ca2,start = 0, end = len(ch)):
while start < end:
if ch[start] == ca1:
ch[end] == ca2
start = start + 1
sentence = "Ceci est une toute petite phrase."
print characterSwitch(sentence, ' ', '*')
print characterSwitch(sentence, ' ', '*', 8, 12)
print characterSwitch(sentence, ' ', '*', 12)
print characterSwitch(sentence, ' ', '*', end = 12)
Assigning len(ch) doesn't seem to work and also I'm pretty sure this isn't the most efficient way of doing this. The following is the output I'm aiming for:
Ceci*est*une*toute*petite*phrase.
Ceci est*une*toute petite phrase.
Ceci est une*toute*petite*phrase.
Ceci*est*une*toute petite phrase.
Are you looking for replace() ?
sentence = "Ceci est une toute petite phrase."
sentence = sentence.replace(' ', '*')
print sentence
# Ceci*sest*sune*stoute*spetite*sphrase.
See a demo on ideone.com additionally.
For your second requirement (to replace only from the 8th to the 12th character), you could do:
sentence = sentence[8:12].replace(' ', '*')
Assuming you have to do it character by character you could do it this way:
sentence = "this is a sentence."
replaced = ""
for c in sentence:
if c == " ":
replaced += "*"
else:
replaced += c
print replaced

Iterating through a text file and searching for keywords in python [duplicate]

I am searching a way to check if there is a blank space next to the found keywords if so break the loop till it again finds the keyword.
For example here, I have a keyword:
'/* Function Declarations */'
If this keyword is found the loop will proceed further and check for the next set of keywords:
['(const ', '(unsigned ', '(char ', '(double ', '(int ', '(long ', '(long long ', '(float ', '(string ', '(signed ', ');']
If this is also satisfied the line will be sent to another function for processing. Until there is an empty space. This is what I wanted to achieve in this function.
But unfortunately it ignores the empty space constrain and it satisfies only the first two
I have herewith attached the function:
def find_member_functions(opened_file, opened_cpp_file):
previous_keyword = '/* Function Declarations */'
member_func_keyword = ['(const ', '(unsigned ', '(char ',
'(double ', '(int ', '(long ',
'(long long ', '(float ', '(string ',
'(signed ', ');']
for line in opened_cpp_file:
prev_keyword_matched = [True for match in prev_keyword if match in line]
if True in prev_keyword_matched:
member_func_keyword_matched = [True for match in member_func_keyword if match in line]
if True in member_func_keyword_matched:
if line == '\n':
print "End of function declaration"
break
else:
found_funcs = member_functions(opened_file, line)
print str(found_funcs)
return
I then edited my code yet, I am not able to achieve what I wanted to. In this code, it says an empty line "End of member functions" even though it is not the end. The line which I am executing is
/* Function Declarations */
extern void multiplyImage(const unsigned char img[2115216], double parameter,
unsigned char imgout[2115216]);
blabla.....
The functions finds the next line as a space though I have the continuation of the function
unsigned char imgout[2115216]);
My edited code:
def Find_Member_Functions(Opened_File, Opened_Cpp_File):
Previous_Line_Keyword = '/* Function Declarations */'
Member_Function_Keyword = ['(const ', '(unsigned ', '(char ', '(double ', '(int ', '(long ', '(long long ', '(float ', '(string ', '(signed ', ');']
Empty_Line = ['\n', '\r\n']
for item in Member_Function_Keyword:
for line in Opened_Cpp_File:
Previous_Line_Keyword_Matched = [True for match in Previous_Line_Keyword if match in line]
if True in Previous_Line_Keyword_Matched:
Member_Function_Keyword_Matched = [True for match in Member_Function_Keyword if match in line]
if True in Member_Function_Keyword_Matched:
Found_Functions = Member_Functions(Opened_File, line)
print str(Found_Functions)
Next_Line = line[1:]
Empty_Line_Matched = [True for match in Empty_Line if match in Next_Line]
if True in Empty_Line_Matched:
print "End of member functions"
break
else:
pass
return
I couldn't understand where I am going wrong. It would be great to have some guidance...
My command line output
extern void multiplyImage(const unsigned char img[2115216], double
parameter,
End of member functions
unsigned char imgout[2115216]);
End of member functions
This part of your code:
Next_Line = line[1:]
Empty_Line_Matched = [True for match in Empty_Line if match in Next_Line]
Makes absolutely no sense, for three principal reasons:
line[1:] isn't the next line, it's just same line less its first character;
For blank lines line == '\n', the first character is '\n', so line[1:] == "" and therefore Next_Line doesn't contain a newline character; and
'\n' is at the end of every line, so Empty_Line_Matched will contain True in every case except a blank line (see #2).

Check if there is an empty space after a keyword and break if found in python

I am searching a way to check if there is a blank space next to the found keywords if so break the loop till it again finds the keyword.
For example here, I have a keyword:
'/* Function Declarations */'
If this keyword is found the loop will proceed further and check for the next set of keywords:
['(const ', '(unsigned ', '(char ', '(double ', '(int ', '(long ', '(long long ', '(float ', '(string ', '(signed ', ');']
If this is also satisfied the line will be sent to another function for processing. Until there is an empty space. This is what I wanted to achieve in this function.
But unfortunately it ignores the empty space constrain and it satisfies only the first two
I have herewith attached the function:
def find_member_functions(opened_file, opened_cpp_file):
previous_keyword = '/* Function Declarations */'
member_func_keyword = ['(const ', '(unsigned ', '(char ',
'(double ', '(int ', '(long ',
'(long long ', '(float ', '(string ',
'(signed ', ');']
for line in opened_cpp_file:
prev_keyword_matched = [True for match in prev_keyword if match in line]
if True in prev_keyword_matched:
member_func_keyword_matched = [True for match in member_func_keyword if match in line]
if True in member_func_keyword_matched:
if line == '\n':
print "End of function declaration"
break
else:
found_funcs = member_functions(opened_file, line)
print str(found_funcs)
return
I then edited my code yet, I am not able to achieve what I wanted to. In this code, it says an empty line "End of member functions" even though it is not the end. The line which I am executing is
/* Function Declarations */
extern void multiplyImage(const unsigned char img[2115216], double parameter,
unsigned char imgout[2115216]);
blabla.....
The functions finds the next line as a space though I have the continuation of the function
unsigned char imgout[2115216]);
My edited code:
def Find_Member_Functions(Opened_File, Opened_Cpp_File):
Previous_Line_Keyword = '/* Function Declarations */'
Member_Function_Keyword = ['(const ', '(unsigned ', '(char ', '(double ', '(int ', '(long ', '(long long ', '(float ', '(string ', '(signed ', ');']
Empty_Line = ['\n', '\r\n']
for item in Member_Function_Keyword:
for line in Opened_Cpp_File:
Previous_Line_Keyword_Matched = [True for match in Previous_Line_Keyword if match in line]
if True in Previous_Line_Keyword_Matched:
Member_Function_Keyword_Matched = [True for match in Member_Function_Keyword if match in line]
if True in Member_Function_Keyword_Matched:
Found_Functions = Member_Functions(Opened_File, line)
print str(Found_Functions)
Next_Line = line[1:]
Empty_Line_Matched = [True for match in Empty_Line if match in Next_Line]
if True in Empty_Line_Matched:
print "End of member functions"
break
else:
pass
return
I couldn't understand where I am going wrong. It would be great to have some guidance...
My command line output
extern void multiplyImage(const unsigned char img[2115216], double
parameter,
End of member functions
unsigned char imgout[2115216]);
End of member functions
This part of your code:
Next_Line = line[1:]
Empty_Line_Matched = [True for match in Empty_Line if match in Next_Line]
Makes absolutely no sense, for three principal reasons:
line[1:] isn't the next line, it's just same line less its first character;
For blank lines line == '\n', the first character is '\n', so line[1:] == "" and therefore Next_Line doesn't contain a newline character; and
'\n' is at the end of every line, so Empty_Line_Matched will contain True in every case except a blank line (see #2).

Categories

Resources