In python (2.6) is it possilbe to "join" print output with the previous line of print output? The trailing comma syntax ( print x,) doesn't work because most of the output should have a new line.
for fc in fcs:
count = getCount(fc)
print '%s records in %s' % ('{0:>9}'.format(count),fc)
if count[0] == '0':
delete(fc)
print '==> %s removed' % (fc)
current console output:
3875 records in Aaa
3875 records in Bbb
0 records in Ccc
==> Ccc removed
68675 records in Ddd
desired result:
3875 records in Aaa
3875 records in Bbb
0 records in Ccc ==> Ccc removed
68675 records in Ddd
import sys
sys.stdout.write("hello world")
print writes to the apps standard out and adds a newline.
However you sys.stdout is already a file object pointing to the same location and the write() function of a file object doesn't automatically append a newline to the output string so it should be exactly what you want.
You're asking if a print statement can remove the newline from the end of the previous line. The answer is no.
But you can write:
if count[0] == '0':
removed = ' ==> %s removed' % (fc)
else:
removed = ''
print '%s records in %s%s' % ('{0:>9}'.format(count), fc, removed)
The following should work:
for fc in fcs:
count = getCount(fc)
print '%s records in %s' % ('{0:>9}'.format(count),fc),
if count[0] == '0':
delete(fc)
print '==> %s removed' % (fc)
else:
print ''
There isn't a very good way to shorten that an maintain readability with the delete() in there.
While Python 2 doesn’t have the feature you look for, Python 3 has.
so you can do
from __future__ import print_function
special_ending = '==> %s removed\n' % (fc)
ending = special_ending if special_case else "\n"
print('%s records in %s' % ('{0:>9}'.format(count),fc), end=ending)
Related
I'm writing a script that parses log files and matches certain strings like "INFO", "WARN", "SEVERE", etc.
I can do this with out much trouble using the code below.
from sys import argv
from collections import OrderedDict
# Find and catalog each log line that matches these strings
match_strings = ["INFO", "WARN", "SEVERE"]
if len(argv) > 1:
files = argv[1:]
else:
print "ERROR: You must provide at least one log file to be processed."
print "Example:"
print "%s my.log" % argv[0]
exit(2)
for filename in files:
with open(filename) as f:
data = f.read().splitlines()
# Create data structure to handle results
matches = OrderedDict()
for string in match_strings:
matches[string] = []
for i, s in enumerate(data, 1):
for string in match_strings:
if string in s:
matches[string].append('Line %03d: %s' % (i, s,))
for string in matches:
print "\"%s\": %d" % (string, len(matches[string]))
Log files look like:
2014-05-26T15:06:14.597+0000 INFO...
2014-05-26T15:06:14.597+0000 WARN...
2014-05-27T15:06:14.597+0000 INFO...
2014-05-28T15:06:14.597+0000 SEVERE...
2014-05-29T15:06:14.597+0000 SEVERE...
Current output looks like:
"INFO": 2
"WARN": 1
"SEVERE": 2
However, what I'd rather do is have the script collate and print formatted output by date. So, rather than print a simple list (above) we could get something like the following using the sample from above:
Category 2014-05-26 2014-05-27 2014-05-28 2014-05-29
"INFO": 1 1 0 0
"WARN": 1 0 0 0
"SEVERE": 0 0 1 1
Are there any thoughts / suggestions how to accomplish this?
One way of doing this would be to make a class that has variables info, warn, and severe in it. Then make a dictionary where each element is this class with the key being the date. Then when you are parsing your log file you can just find the date and use that as the index for your dictionary and increment the info, warn, and severe as needed.
I show below part of a working script to verify twitter accounts that is giving me the results I want one besides the other, while I want to have them one per line including the title of the find
Example, the first three result are for followers, then how many others are being followed, and in how many lists the user is in, and its giving me the results all in one line something like this:
1350 257 27 and I want it to be as follows
Followers:1,350
Following: 257
Number of lists present: 27
I tried to use " ; " commas, "/n " ; but either it does not work or gives me a 500 Error
Here is the script
All help will be nice
Thank you
................
details = twitter.show_user(screen_name='xxxxxx')
print "content-type: text/html;charset=utf-8"
print
print"<html><head></head><body>"
print (details['followers_count']) #followers
print (details['friends_count'])# following
print (details['listed_count'])# In how many lists
... ....
Instead of the last three print lines, use string formatting to pass in the values.
print "Followers:{}\nFollowing: {}\nNumber of lists present: {}".format(
details['followers_count'], details['friends_count'], details['listed_count']
)
Take a look at the print function. You can write multiple arguments in a tab-separated line like:
print details['followers_count'], details['friends_count'], details['listed_count']
If you want more control over what you print use the join function:
# Add the parts you want to show
stringParts = []
for part in ['followers_count','friends_count','listed_count']:
stringParts.append( part + " = " + str(details[part]) )
seperator = "," # This will give you a comma seperated string
print seperator.join( stringParts )
You can use the % operator
print 'Followers: %s \nFollowing: %s \nNumber of lists present: %s' % (
details['followers_count'], details['friends_count'],
details['listed_count'])
I'm self teaching myself python by delving right in. I'm not sure if a function does this if you leave it empty:
#My first section that pulls a value from a random shuffle of codes
print "\n"
print "-"*10
print 'This is a test of the %s system'% codes[0]
print "-"*10
print "\n"
#My second section that pulls a value from a random shuffle of codes
print "\n"
print "-"*10
print 'This is not a test of the %s system and all is good'% codes[1]
print "-"*10
print "\n"
My question is, is there a way to make it nicer looking and with fewer lines of code? Or am I stuck with having 10 lines of print?
You can use a function:
def print_stuff(what,addendum=''):
print "\n"
print "-"*10
print 'This is a test of the %s system%s' % (what,addendum)
print "-"*10
print "\n"
print_stuff(codes[0])
print_stuff(codes[1],addendum = " and all is good")
Python has quite awesome multiline strings:
def print_it(somethig):
print """
----------
This is a test of the {} system.
----------
""".format(something)
print_it(0)
print_it(1)
Create a function with the index number:
def print_codes(i):
#My first section that pulls a value from a random shuffle of codes
print "\n"
print "-"*10
print 'This is a test of the %s system'% codes[i]
print "-"*10
print "\n"
print_codes(0)
print_codes(1)
Also read this documentation
If you want to show different messages, you can define a function that receives the message to be printed:
def print_message(message):
print "\n"
print "-"*10
print message
print "-"*10
print "\n"
print_message('This is a test of the %s system' % codes[0])
print_message('This is not a test of the %s system and all is good'% codes[1])
I have Python code that pulls info from a sqlite database and then write to a html file. I'm trying to write as preformatted text and the code below places the text in columns like I am try to accomplish, but (obviously) the link is the entire length of the string, including the whitespace to the right from the .ljust.
How can I get it to only link the text of item.title instead of the entire string, plus whitespace?
content += '%s %s' % (item.slug, str(item.title).ljust(25), item.date.ljust(10)
Edit
title = str(item.title)
spaces = ' '*(25-len(title)) if len(title) <= 25 else ''
'%s%s %s' % (item.slug, title, spaces, item.date.ljust(10))
If you must do it on one line, the following should work for you:
content += '%s %s %s' % tuple(itertools.chain((item.slug,),
str(item.title).ljust(25).split(" ", 1), (item.date.ljust(10),)))
However the following should be a little easier to read
values = [item.slug]
values += str(item.title).ljust(25).split(" ", 1)
values.append(item.date.ljust(10))
content += '%s %s %s' % values
Notice I've added one extra space to your formatting string to make up for the one lost to the string split operation.
EDIT: The above code fails when item.title is greater than 25 characters. A revised version is below.
title, spaces = (str(item.title).ljust(25)+" ").split(" ", 1)
content += '%s%s %s' % (item.slug, title,
spaces, item.date.ljust(10))
This version adds a space to the end of the justified title, so the split operation is guaranteed to return a tuple of length 2.
How do I remove 2nd and rest digit after the period from column one?
For example,
HP_000083.21423 N -1 NO 99.8951% 0.000524499999999983
NP_075561.1_1908 N -1 NO 99.9697% 0.000151499999999971
I would like to remove "_1908" from "NP_075561.1_1908"
and "1423 from "HP_000083.21423"
without removing other items from the subsequent columns.
Expected row would be:
HP_000083.2 N -1 NO 99.8951% 0.000524499999999983
NP_075561.1 N -1 NO 99.9697% 0.000151499999999971
Here's my code: Some of you had provided part of this solution in the past.
for line in fname:
line = re.sub('[\(\)\{\}\'\'\,<>]','', line)
line = re.sub(r"(\.\d+)_\d+", r"\1", line)
fields = line.rstrip("\n").split()
outfile.write('%s %s %s %s %s %s\n' % (fields[0],fields[1],fields[2],fields[3],fields[4],(fields[5])))
Thanks in advance guys,
Cheers,
I'd avoid using regular expressions in this case. You can easily make do with standard string methods:
for line in infile:
first_col, rest = line.split(" ", 1)
first_col = first_col[:first_col.index(".") + 2]
output_line = str.join(" ", (first_col, rest))
outfile.write(output_line)
Here is a solution with a pretty minimal change to the code you provided:
for line in fname:
line = re.sub('[\(\)\{\}\'\'\,<>]','', line)
line = re.sub(r"(\.\d)\d*_?\d*", r"\1", line, 1)
fields = line.rstrip("\n").split()
outfile.write('%s %s %s %s %s %s\n' % (fields[0],fields[1],fields[2],fields[3],fields[4],(fields[5])))