String formatting in Python -textwrapper - python

I have a list of People=[Tom,Mike,Carol] and I want to print it in the the below format.
People Tom
Mike
Carol
Basically its the Title (People) some fixed tabs and then a list of the name in new line ( it sorta looks like a table). I want to achieve this using textwrap in Python but if there is any other possibility, I am open to that as well.
dedented_text = textwrap.dedent(' This is a test sentecne to see how well the textwrap works and hence using it here to test it').strip()
for width in [ 20 ]:
h='{0: <4}'.format('f')
k='{0: >4}'.format(textwrap.fill(dedented_text, width=20))
print h+k
Output:
f This is a test
sentecne to see how
well the textwrap
works and hence
using it here to
test it
Above i added my code for printing the Category and a sentence. But i'm not able to achieve what I want

Just print the first line separately then print the others in a loop:
print 'People ' + people[0]
for i in range(1, len(people)):
print ' ' * 7 + people[i]

Related

How to find required word in novel in python?

I have a text and I have got a task in python with reading module:
Find the names of people who are referred to as Mr. XXX. Save the result in a dictionary with the name as key and number of times it is used as value. For example:
If Mr. Churchill is in the novel, then include {'Churchill' : 2}
If Mr. Frank Churchill is in the novel, then include {'Frank Churchill' : 4}
The file is .txt and it contains around 10-15 paragraphs.
Do you have ideas about how can it be improved? (It gives me error after some words, I guess error happens due to the reason that one of the Mr. is at the end of the line.)
orig_text= open('emma.txt', encoding = 'UTF-8')
lines= orig_text.readlines()[32:16267]
counts = dict()
for line in lines:
wordsdirty = line.split()
try:
print (wordsdirty[wordsdirty.index('Mr.') + 1])
except ValueError:
continue
Try this:
text = "When did Mr. Churchill told Mr. James Brown about the fish"
m = [x[0] for x in re.findall('(Mr\.( [A-Z][a-z]*)+)', text)]
You get:
['Mr. Churchill', 'Mr. James Brown']
To solve the line issue simply read the entire file:
text = file.read()
Then, to count the occurrences, simply run:
Counter(m)
Finally, if you'd like to drop 'Mr. ' from all your dictionary entries, use x[0][4:] instead of x[0].
This can be easily done using regex and capturing group.
Take a look here for reference, in this scenario you might want to do something like
# retrieve a list of strings that match your regex
matches = re.findall("Mr\. ([a-zA-Z]+)", your_entire_file) # not sure about the regex
# then create a dictionary and count the occurrences of each match
# if you are allowed to use modules, this can be done using Counter
Counter(matches)
To access the entire file like that, you might want to map it to memory, take a look at this question

How to print specific words in colour on python?

I want to print a specific word a different color every time it appears in the text. In the existing code, I've printed the lines that contain the relevant word "one".
import json
from colorama import Fore
fh = open(r"fle.json")
corpus = json.loads(fh.read())
for m in corpus['smsCorpus']['message']:
identity = m['#id']
text = m['text']['$']
strtext = str(text)
utterances = strtext.split()
if 'one' in utterances:
print(identity,text, sep ='\t')
I imported Fore but I don't know where to use it. I want to use it to have the word "one" in a different color.
output (section of)
44814 Ohhh that's the one Johnson told us about...can you send it to me?
44870 Kinda... I went but no one else did, I so just went with Sarah to get lunch xP
44951 No, it was directed in one place loudly and stopped when I stoppedmore or less
44961 Because it raised awareness but no one acted on their new awareness, I guess
44984 We need to do a fob analysis like our mcs onec
Thank you
You could also just use the ANSI color codes in your strings:
# define aliases to the color-codes
red = "\033[31m"
green = "\033[32m"
blue = "\033[34m"
reset = "\033[39m"
t = "That was one hell of a show for a one man band!"
utterances = t.split()
if "one" in utterances:
# figure out the list-indices of occurences of "one"
idxs = [i for i, x in enumerate(utterances) if x == "one"]
# modify the occurences by wrapping them in ANSI sequences
for i in idxs:
utterances[i] = red + utterances[i] + reset
# join the list back into a string and print
utterances = " ".join(utterances)
print(utterances)
If you only have 1 coloured word you can use this I think, you can expand the logic for n coloured words:
our_str = "Ohhh that's the one Johnson told us about...can you send it to me?"
def colour_one(our_str):
if "one" in our_str:
str1, str2 = our_str.split("one")
new_str = str1 + Fore.RED + 'one' + Style.RESET_ALL + str2
else:
new_str = our_str
return new_str
I think this is an ugly solution, not even sure if it works. But it's a solution if you can't find anything else.
i use colour module from this link or colored module that link
Furthermore if you dont want to use a module for coloring you can address to this link or that link

Using regular expressions in python to extract location mentions in a sentence

I am writing a code using python to extract the name of a road,street, highway, for example a sentence like "There is an accident along Uhuru Highway", I want my code to be able to extract the name of the highway mentioned, I have written the code below.
sentence="there is an accident along uhuru highway"
listw=[word for word in sentence.lower().split()]
for i in range(len(listw)):
if listw[i] == "highway":
print listw[i-1] + " "+ listw[i]
I can achieve this but my code is not optimized, i am thinking of using regular expressions, any help please
'uhuru highway' can be found as follows
import re
m = re.search(r'\S+ highway', sentence) # non-white-space followed by ' highway'
print(m.group())
# 'uhuru highway'
If the location you want to extract will always have highway after it, you can use:
>>> sentence = "there is an accident along uhuru highway"
>>> a = re.search(r'.* ([\w\s\d\-\_]+) highway', sentence)
>>> print(a.group(1))
>>> uhuru
You can do the following without using regexes:
sentence.split("highway")[0].strip().split(' ')[-1]
First split according to "highway". You'll get:
['there is an accident along uhuru', '']
And now you can easily extract the last word from the first part.

Removing spaces from For Loop in Python

When creating a for loop, it appears that python adds spaces.
menuItems = ['apple', 'banana', 'car', 'thing', 'whatever', 'burrito']
menuNum = 1
for menuItem in menuItems:
print menuNum,'. ',menuItem
menuNum = menuNum + 1
returns this
1 . apple
2 . banana
3 . car
etc...
Any idea on how I can simply get this without the spacing?
eg.
1. apple
2. banana
3. car
Use string formatting. print in Python 2 puts a space for each comma used to separate the items.
>>> data = ['apple', 'banana', 'car', 'thing', 'whatever', 'burrito']
for i, item in enumerate(data, 1):
print '{}. {}'.format(i, item)
...
1. apple
2. banana
3. car
4. thing
5. whatever
6. burrito
And use enumerate if you want index as well items.
Use one of Python's formatting capabilities.
print "{} . {}".format(menuNum, menuItem) # 2.7+ or 3.x
print "%d . %s" % (menuNum, menuItem)
The print expression in Python 2 puts spaces between the items on a single line. To avoid this, create a single string first that looks like you want to output to appear:
# string formatting
for menuItem in menuItems:
print '{0}. {1}'.format(menuNum, menuItem)
Or else, use the Python3 print function, which has more options available.
# print function
from __future__ import print_function
for menuItem in menuItems:
print(menuNum, '. ', menuItem, sep='')
Just use:
from __future__ import print_function
print(menuNum, '. ', menuItem, sep='')
You could also use string formatting:
print '{0}. {1}'.format(menuNum, menuItem)
You have a space after the ". " when using a comma and printing, a space is inserted for you.
Altough I use python 3.3, as far as I'm aware, using '+' should still work. Unless I'm missing something; the following would work fine.
print menuNum + '.' + menuItem

Python: Formatting a list (which contains a list) for printing

I'm working on a project that translates input to Pig Latin (yeah, I'm sure you've never seen this one before...) and having trouble formatting my output.
(for the following, sentence = a list holding user input (phrase), split by phrase.split() )
sentence.remove(split)
final = map(str,sentence)
print "Final is (before formatting:", final
final = [sentence[0].capitalize()] , sentence[1:]
#finalFormat = ' '.join(final)
print "Final is", str(final).strip('[]')
#print "FinalFormat is", finalFormat
print "In Pig Latin, you said \"", ' '.join(map(str, final)), "\". Oink oink!"
What I get is:
"In Pig Latin, you said "['Firstword'] ['secondword', 'thirdword'] "
What I am looking for is:
"In Pig Latin, you said "Firstword secondword thirdword."
Based on my debug print statements it looks like my problem is still on the line (5 from the bottom):
final = [sentence[0].capitalize()] , sentence[1:]
Thanks in advance!
Change this line:
final = sentence[0].capitalize() , sentence[1:]
To this:
final = [sentence[0].capitalize()] + sentence[1:]
You were mapping a tuple of a string and a list, to strings, rather than a list.
Note: using 'single"' quotes here will avoid "this\"" ugliness.

Categories

Resources