This code below creates a 1D image of a race track:
def displayTrack(position):
output=''#value given to output
track=[' ']*20# track is initially just a bunch of empty spaces
track[position]= 'r'#AND track also contains an r icon
print(' -'*20)#these are the top and bottom borders
print('0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J')#these represent each individual cell
for i in range(len(track)):
output= output +track[i] +'|'#append a "|" before and after each empty space " "
print (output)#print the result
print(' -'*20)
If you run this code you will be able to view the image. If you look at the charachter "r" you will see that to the right of charachter "r" there is "|" character. I need to implement a "|" on the left side of runner as well. I need to use a method similar to above because the initial states of many of the variables and the image depends on other variables,etc.
I know the problem exists in the fate that output= ''. If instead output was not a space, or not a charachter at all then the image would display properly but I do not know how to make it so. Can someone please give me a hand. Any and all help is appreciated.
If anything is unclear please let me know an I will change it as soon as possible.
EDIT: So I figured out that the new code should look something like this: There are 3 changes:
1) output='|' instead of ''
2) in the strings that contain the hyphens as well as the alphanumeric charachters, the space at the end is moved to the beginning instead. This fixes all the problems.
Is this what you want ? It is unclear, since your original layout is strange.
def displayTrack(position):
output='|'#value given to output
track=[' ']*20# track is initially just a bunch of empty spaces
track[position]= 'r'#AND track also contains an r icon
print(' -'*20)#these are the top and bottom borders
print(' 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J')#these represent each individual cell
for i in range(len(track)):
output= output +track[i] +'|'#append a "|" before and after each empty space " "
print (output)#print the result
print(' -'*20)
Your comment #append a "|" before and after each empty space " " is misleading. What the statement before it does, is add a part of the track and a "|". It doesn't look if the character is a space, and doesn't put anything before it. The only reason there are |'s before the spaces is because they follow a position which has one after it.
To put something before the rest, start with output = '|' instead of ''. You may want to put an extra space before the other lines as well in that case, to keep things lined up. For example: print (' ' + ' -' * 20)
Related
I am trying to replace
'AMAT_0000006951_10Q_20200726_Filing Section: Risk'
with:
'AMAT 10Q Filing Section: Risk'
However, everything up until Filing Section: Risk will be constantly changing, except for positioning. I just want to pull the characters from position 0 to 5 and from 15 through 19.
df['section'] = df['section'].str.replace(
I'd like to manipulate this but not sure how?
Any help is much appreciated!
Given your series as s
s.str.slice(0, 5) + s.str.slice(15, 19) # if substring-ing
s.str.replace(r'\d{5}', '') # for a 5-length digit string
You may need to adjust your numbers to index properly. If that doesn't work, you probably want to use a regular expression to get rid of some length of numbers (as above, with the example of 5).
Or in a single line to produce the final output you have above:
s.str.replace(r'\d{10}_|\d{8}_', '').str.replace('_', ' ')
Though, it might not be wise to replace the underscores. Instead, if they change, explode the data into various columns which can be worked on separately.
If you want to replace a fix length/position of chars, use str.slice_replace to replace
df['section'] = df['section'].str.slice_replace(6, 14, ' ')
Other people would probably use regex to replace pieces in your string. However, I would:
Split the string
append the piece if it isn't a number
Join the remaining data
Like so:
s = 'AMAT_0000006951_10Q_20200726_Filing Section: Risk'
n = []
for i in s.split('_'):
try:
i = int(i)
except ValueError:
n.append(i)
print(' '.join(n))
AMAT 10Q Filing Section: Risk
Edit:
Re-reading your question, if you are just looking to substring:
Grabbing the first 5 characters:
s = 'AMAT_0000006951_10Q_20200726_Filing Section: Risk'
print(s[:4]) # print index 0 to 4 == first 5
print(s[15:19]) # print index 15 to 19
print(s[15:]) # print index 15 to the end.
If you would like to just replace pieces:
print(s.replace('_', ' '))
you could throw this in one line as well:
print((s[:4] + s[15:19] + s[28:]).replace('_', ' '))
'AMAT 10Q Filing Section: Risk'
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
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]
I have a .csv file which looks like:
['NAME' " 'RA_I1'" " 'DEC_I1'" " 'Mean_I1'" " 'Median_I1'" " 'Mode_I1'" ...]"
where this string carries on for (I think) 95 entries, the entire file is over a thousand rows deep. I want to remove all the characters: [ ' " and just have everything separated by a single white space entry (' ').
So far I've tried:
import pandas as pd
df1 = pd.read_table('slap.txt')
for char in df1:
if char in " '[":
df1.replace(char, '')
print df1
Where I'm just 'testing' the code to see if it will do what I want it to, it's not. I'd like to implement it on the entire file, but I'm not sure how.
I've checked this old post out but not quite getting it to work for my purposes. I've also played with the linked post, the only problem with it seems to be that all the entries are spaced twice rather than just once....
This looks like something you ought to be able to grab with a (not particularly pretty) regular expression in the sep argument of read_csv:
In [11]: pd.read_csv(file_name, sep='\[\'|\'\"\]|[ \'\"]*', header=None)
Out[11]:
0 1 2 3 4 5 6 7
0 NaN NAME RA_I1 DEC_I1 Mean_I1 Median_I1 Mode_I1 NaN
You can play about with the regular expression til it truly fits your needs.
To explain this one:
sep = ('\[\' # each line startswith [' (the | means or)
'|\'\"\]' # endswith '"] (at least the one I had)
'|[ \'\"]+') # this is the actual delimiter, the + means at least one, so it's a string of ", ' and space in any order.
You can see this hack has left a NaN column at either end. The main reason this is pretty awful is because of the inconsistency of your "csv", I would definitely recommend cleaning it up, of course, one way to do that is just to use pandas and then to_csv. If it's generated by someone else... complain (!).
Have you tried:
string.strip(s[, chars])
?
http://docs.python.org/2/library/string.html
New to python, need some help with my program. I have a code which takes in an unformatted text document, does some formatting (sets the pagewidth and the margins), and outputs a new text document. My entire code works fine except for this function which produces the final output.
Here is the segment of the problem code:
def process(document, pagewidth, margins, formats):
res = []
onlypw = []
pwmarg = []
count = 0
marg = 0
for segment in margins:
for i in range(count, segment[0]):
res.append(document[i])
text = ''
foundmargin = -1
for i in range(segment[0], segment[1]+1):
marg = segment[2]
text = text + '\n' + document[i].strip(' ')
words = text.split()
Note: segment [0] means the beginning of the document, and segment[1] just means to the end of the document if you are wondering about the range. My problem is when I copy text to words (in words=text.split() ) it does not retain my blank lines. The output I should be getting is:
This is my substitute for pistol and ball. With a
philosophical flourish Cato throws himself upon his sword; I
quietly take to the ship. There is nothing surprising in
this. If they but knew it, almost all men in their degree,
some time or other, cherish very nearly the same feelings
towards the ocean with me.
There now is your insular city of the Manhattoes, belted
round by wharves as Indian isles by coral reefs--commerce
surrounds it with her surf.
And what my current output looks like:
This is my substitute for pistol and ball. With a
philosophical flourish Cato throws himself upon his sword; I
quietly take to the ship. There is nothing surprising in
this. If they but knew it, almost all men in their degree,
some time or other, cherish very nearly the same feelings
towards the ocean with me. There now is your insular city of
the Manhattoes, belted round by wharves as Indian isles by
coral reefs--commerce surrounds it with her surf.
I know the problem happens when I copy text to words, since it doesn't keep the blank lines. How can I make sure it copies the blank lines plus the words?
Please let me know if I should add more code or more detail!
First split on at least 2 newlines, then split on words:
import re
paragraphs = re.split('\n\n+', text)
words = [paragraph.split() for paragraph in paragraphs]
You now have a list of lists, one per paragraph; process these per paragraph, after which you can rejoin the whole thing into new text with double newlines inserted back in.
I've used re.split() to support paragraphs being delimited by more than 2 newlines; you could use a simple text.split('\n\n') if there are ever only going to be exactly 2 newlines between paragraphs.
use a regexp to find the words and the blank lines rather than split
m = re.compile('(\S+|\n\n)')
words=m.findall(text)