Including Exception in python - python

I have a file at /location/all-list-info.txt underneath I have some items in below manner:
aaa:xxx:abc.com:1857:xxx1:rel5t2:y
ifa:yyy:xyz.com:1858:yyy1:rel5t2:y
I process these items with a below python code:
def pITEMName():
global itemList
itemList = str(raw_input('Enter pipe separated list of ITEMS : ')).upper().strip()
items = itemList.split("|")
count = len(items)
print 'Total Distint Item Count : ', count
pipelst = itemList.split('|')
filepath = '/location/all-item-info.txt '
f = open(filepath, 'r')
for lns in f:
split_pipe = lns.split(':', 1)
if split_pipe[0] in pipelst:
index = pipelst.index(split_pipe[0])
del pipelst[index]
for lns in pipelst:
print lns,' is wrong item Name'
f.close()
if podList:
After execution of above python code its gives a prompt as :
Enter pipe separated list of ITEMS:
And then I passes the items :
Enter pipe separated list of ITEMS: aaa|ifa-mc|ggg-mc
now after pressing enter above code process further like below :
Enter pipe separated list of ITEMS : aaa|ifa-mc|ggg-mc
Total Distint Item Count : 3
IFA-MC is wrong Item Name
GGG-MC is wrong Item Name
ITEMs Belonging to other Centers :
Item Count From Other Center = 0
ITEMs Belonging to Current Centers :
Active Items in US1 :
^IFA$
Test Active Items in US1 :
^AAA$
Ignored Item Count From Current center = 0
You Have Entered ItemList belonging to this center as: ^IFA$|^AAA$
Active Pod Count : 2
My question is if I suffix the '-mc' in items while giving the input its given me as wrong item whereas it presents in /location/all-item-info.txt file with not present the item in /location/all-item-info.txt . Please have a look at below output again :
IFA-MC is wrong Item Name
GGG-MC is wrong Item Name
In above example 'ifa' is present in /location/all-items-info.txt path whereas as ggg is not present.
Request you to help me here what can I do on above code so if I suffix the -mc which are present in /location/all-items-info.txt file it should not count as wrong item name. it should count only for those items which are not present in /location/all-items-info.txt file.
Please give you help.
Thanks,
Ritesh.

If you want to avoid checking for -mc as well, then you can modify this part of your script -
pipelst = itemList.split('|')
To -
pipelst = [i.split('-')[0] for i in itemList.split('|')]

It's a bit unclear exactly what you are asking, but basically to ignore any '-mc' from user input, you can explicitly preprocess the user input to strip it out:
pipelst = itemList.split('|')
pipelst = [item.rsplit('-mc',1)[0] for item in pipelst]
If instead you want to allow for the possibility of -mc-suffixed words in the file as well, simply add the stripped version to the list instead of replacing
pipelst = itemList.split('|')
for item in pipelist:
if item.endswith('-mc'):
pipelst.append(item.rsplit('-mc',1)[0])
Another issue may be based on the example lines you gave from /location/all-list-info.txt, it sounds like all the items are lowercase. However, pipelst is explicitly making the user input all uppercase. String equality and in mechanics is case-sensitive, so for instance
>>> print 'ifa-mc' in ['IFA-MC']
False
You probably want:
itemList = str(raw_input('Enter pipe separated list of ITEMS : ')).lower().strip()
and you could use .upper() only when printing or wherever it is needed
Finally, there are a few other things that could be tweaked with the code just to make things a bit faster and cleaner. The main one that comes to mind is it seems like pipelst should be a python set and not a list as checking inclusion and removal would then be much faster for large lists, and the code to remove an item from a set is much cleaner:
>>> desserts = set(['ice cream', 'cookies', 'cake'])
>>> if 'cake' in desserts:
... desserts.remove('cake')
>>> print desserts
set(['cookies', 'ice cream'])

Related

Basic Python Issue / removing whitespace

I am struggling in a python undergraduate class that should have had fewer modules: for a grade, I have a code that reads a formatted file and "prints" a table. The problem is, the last entry of the table has a trailing space at the end. My print statement is
for time in movieTiming[m]:
print(time, end=" ")
I really have no idea what to do here: i have a list that contains something like "11:30", "10:30", "9:00", and it should be printed as 11:30 10:30 9:00 (with no space after the 9:00). I have tried to join my list, but really, most of the concepts I need to do all of this were never even communicated or taught in the class. I guess that's how it goes, but I'm struggling. My approach is to appropriate existing code, try to understand it, and learn that way, but it's not making any sense to me.
I am taking Java I at the same time, and Java makes sense to me because the pace of the Java course is about 1/2 of the pace of the Python class: 2x the modules means 1/2 the time. If anyone can help, thank you.
Here's what I have (I'll remove the notes if it's not helpful?)
# First we open the file named "movies.csv" using the open()
f = open(input())
# f.readlines() reads the contents of the file and stores each line as a separate element in a list named movies.
movies = f.readlines()
# Next we declare 2 dictionaries named movieTiming and movieRating.
# movieTiming will store the timing of each movie.
# The key would be the movie name and the value would be the list of timings of the movie.
movieTiming = {}
# movieRating will store the rating of each movie.
# key would be the movie name and the value would be the rating of the respective movie.
movieRating = {}
# Now we traverse through the movies list to fill our dictionaries.
for m in movies:
# First we split each line into 3 parts that is, we split the line whenever a comma(",") occurs.
# split(",") would return a list of splitted words.
# For example: when we split "16:40,Wonders of the World,G", it returns a list ["16:40","Wonders of the World","G"]
movieDetails = m.split(",")
# movieDetails[1] indicates the movie name.
# So if the movie name is not present in the dictionary then we initialize the value with an empty list.
#need a for loop
if(movieDetails[1] not in movieTiming):
movieTiming[movieDetails[1]] = []
# movieDetails[0] indicates the timing of the movie.
# We append the time to the existing list of the movie.
movieTiming[movieDetails[1]].append(movieDetails[0])
# movieDetails[2] indicates the rating of the movie.
# We use strip() since a new line character will be appended at the end of the movie rating.
# So to remove the new line character at the end we use strip() and we assign the rating to the respective movie.
movieRating[movieDetails[1]] = movieDetails[2].strip()
# Now we traverse the movieRating dictionary.
for m in movieRating:
# In -44.44s, negative sign indicates left justification.
# 44 inidcates the width assigned to movie name.
# .44 indicates the number of characters allowed for the movie name.
# s indicates the data type string.
# print() generally prints a message and prints a new line at the end.
# So to avoid this and print the movie name, rating and timing in the same line, we use end=" "
# end is used to print all in the same line separated by a space.
print("%-44.44s"%m,"|","%5s"%movieRating[m],"|",end=" ")
# Now we traverse through the movieTiming[m] which indicates the list of timing for the particular movie m.
for time in movieTiming[m]:
print(time, end=" ")
# This print() will print a new line to print the next movie details in the new line.
print()
Instead of multiple calls to print, create a single space-delimited string with ' '.join and print that.
print(' '.join(movieTiming[m]))
As you've noted, printing a space between list elements is different from printing a space after each element. While you can play around with list indices to figure out which element is the last element and avoid printing a space after it, the join method already handles the corner cases for you.
Similar to what you tried, though, consider an approach not of printing a space after all but the last element, but printing a space before all but the first.
print(movieTiming[m][0], end='')
for t in movieTiming[m][1:]:
print(f' {t}', end=''
print()
I mention this not because you should consider it an alternative to str.join, but because it helps to think about your problem in different ways.
This might help:
my_list = ['11:00', '12:30', '13:00']
joined = ' '.join(my_list)
print(joined)
# 11:00 12:30 13:00
Supposed you have:
time = ["19:30","19:00","18:00"]
then you could apply the list as separate arguments:
print(*time)
You can, as always, control the separator by setting the sep keyword argument:
print(*time, sep=', ')
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():
joined_string = ' '.join([str(v) for v in time])
print(joined_string)

Need to Get 4 URLs in Output After Remove Letter S but Get only Last URL

Below 4 URLs Contain Letter s and We need to remove this Letter and
Print the 4 x URLs But The Problem is I got only the last web site not the 4
Sites printed
Note :Language used is Python
file1 = ['https:/www.google.com\n', 'https:/www.yahoo.com\n', 'https:/www.stackoverflow.com\n',
'https:/www.pythonhow.com\n']
file1_remove_s = []
for line in file1:
file1_remove_s = line.replace('s','',1)
print(file1_remove_s)
You are reassigning file1_remove_s from a list object to the modified list element. You want to use append instead
file1 = ['https:/www.google.com\n', 'https:/www.yahoo.com\n', 'https:/www.stackoverflow.com\n',
'https:/www.pythonhow.com\n']
file1_remove_s = []
for line in file1:
file1_remove_s.append(line.replace('s','',1))
print(file1_remove_s)
You are assigning only the last item on the dict by using the = operator. This is actually a perfect place to use a list comprehension, hence your code should look like:
file1 = [file1_remove_s.replace('s','',1) for file1_remove_s in file1]
This will automatically append the formatted text -strings with removed "s" - to a list and by setting the variable name of that list to the name of the initial list, the initial list gets overwritten by the new one which have the proper format of the texts you want.

Should I Append or Join a list of dict and And how in python?

Using this code I was able to cycle through several instances of attributes and extract First and Last name if they matched the criteria. The results are a list of dict. How would i make all of these results which match the criteria, return as a full name each on it's own line as text?
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
print({players['firstName'], players['lastName']})
Results of Print Statement
{'Chandon', 'Sullivan'}
{'Urban', 'Brent'}
Are you looking for this:
print(players['firstName'], players['lastName'])
This would output:
Chandon Sullivan
Urban Brent
Your original trial just put the items to a set {}, and then printed the set, for no apparent reason.
Edit:
You can also for example join the firstName and lastName to be one string and then append the combos to a lists. Then you can do whatever you need with the list:
names = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
names.append(f"{players['firstName']} {players['lastName']}")
If you're using a version of Python lower than 3.6 and can't use f-strings you can do the last line for example like this:
names.append("{} {}").format(players['firstName'], players['lastName'])
Or if you prefer:
names.append(players['firstName'] + ' ' + players['lastName'])
Ok I figured out by appending the first and last name and creating a list for the found criteria. I then converted the list to a string to display it on the device.
full_list = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
full_list.append((players['firstName'] + " " + players['lastName']))
send_message('\n'.join(str(i) for i in full_list))

Python help. Finding largest value in a file and printing out value w name

I need to create a progtam that opens a file then reads the values inside the file and then prints out the name with the largest value.
The file contains the following info:
Juan,27
Joe,16
Mike,29
Roy,10
Now the code I have is as follows:
UserFile=input('enter file name')
FileOpen=open(User File,'r')
for lines in User File:
data=line.split(",")
name=data[0]
hrs=data[1]
hrs=int(hrs)
LHRS = 0
if hrs > LHRS:
LHRS = hrs
if LHRS == LHRS:
print('Person with largest hours is',name)
The following prints out :
Person with the largest hours is Juan
Person with the largest hours is Mike
How can I make it so it only prints out the true largest?
While your effort for a first timer is pretty impressive, what you're unable to do here is.. Keep track of the name WHILE keeping track of the max value! I'm sure it can be done in your way, but might I suggest an alternative?
import operator
Let's read in the file like how I've done. This is good practice, this method handles file closing which can be the cause of many problems if not done properly.
with open('/Users/abhishekbabuji/Desktop/example.txt', 'r') as fh:
lines = fh.readlines()
Now that I have each line in a list called lines, it also has this annoying \n in it. Let's replace that with empty space ''
lines = [line.replace("\n", "") for line in lines]
Now we have a list like this. ['Name1, Value1', 'Name2, Value2'..] What I intend to do now, is for each string item in my list, take the first part in as a key, and the integer portion of the second part as the value to my dictionary called example_dict. So in 'Name1, Value1', Name1 is the item in index 0 and Name2 is my item in index 1 when I turn this into a list like I've done below and added the key, value pair into the dictionary.
example_dict = {}
for text in lines:
example_dict[text.split(",")[0]] = int(text.split(",")[1])
print(example_dict)
Gives:
{'Juan': 27, 'Joe': 16, 'Mike': 29, 'Roy': 10}
Now, obtain the key whose value is max and print it.
largest_hour = max(example_dict.items(), key=operator.itemgetter(1))[1]
highest_key = []
for person, hours in example_dict.items():
if hours == largest_hour:
highest_key.append((person, hours))
for pair in highest_key:
print('Person with largest hours is:', pair[0])

Matching regex to list items in Python

I am attempting to write a python script that shows the URL flow on my installation of nginx. So I currently have my script opening my 'rewrites' file that contains a list of of regex's and locations like so:
rewritei ^/ungrad/info.cfm$ /ungrad/info/ permanent;
So what I currently have python doing is reading the file, trimming the first and last word off (rewritei and premanent;) which just leaves a list like so:
[
['^/ungrad/info.cfm$', '/ungrad/info'],
['^/admiss/testing.cfm$', '/admiss/testing'],
['^/ungrad/testing/$', '/ungrad/info.cfm']
]
This results in the first element being the URL watched, and the second being the URL redirected to. What I would like to do now, is take each of the first elements, and run the regex over the entire list, and check if it matches any of the second elements.
With the example above, [0][0] would match [2][1].
However I am having trouble thinking of a good and efficient way to do this.
import re
a = [
['^/ungrad/info.cfm$', '/ungrad/info'],
['^/admiss/testing.cfm$', '/admiss/testing'],
['^/ungrad/testing/$', '/ungrad/info.cfm']
]
def matchingfun(b):
for list1 in a: # iterating the main list
for reglist in list1: # iterating the inner lists
count = 0
matchedurl = []
for innerlist in reglist[:1]: # iterating the inner list items
c = b.match(innerlist) # matching the regx
if c:
count = count+1
if count > 0:
matchedurl.append(reglist)
return matchedurl
result1 = []
for list1 in a:
for reglist in list1:
b = re.compile(reglist[0])
result = matchingfun(b)
result1.extend(result)
bs = list(set(result1))
print "matched url is", bs
This is bit unefficient i guess but I have done to some extent. Hope this answers your query. the above snippet prints the urls which are matched with the second items in the entire list.

Categories