detect an alphabetical character in a picture using JES - python

I have a task that asked me to making two TEXT picture 1 which one of them is only one character 2 to detect on the TEXT picture.
the first task is to detect only one character location and I sorted it out, but the second task is to detect all the characters location in it.
It says that I have to copy, and paste the detectOneChar() and extend it by numbers of alphabetical including "space" meaning 27 times. but I did not understand how to do.
This is my first code:
def driver():
src=makePicture(pickAFile())
tgt=makePicture(pickAFile())
for myOffset in range(0,getWidth(tgt)-getWidth(src)):
detectOneChar(src,tgt,myOffset,0)
explore(tgt)
return tgt
def detectOneChar(src,tgt,xOffset,yOffset):
sWidth=getWidth(src)
sHeight=getHeight(src)
matchPixels=0
perfectMatch=sWidth*sHeight
for sX in range (0,sWidth):
for sY in range (0,sHeight):
tX=sX+xOffset
tY=sY+yOffset
sPx=getPixel(src,sX,sY)
tPx=getPixel(tgt,tX,tY)
if getColor(tPx) == getColor(sPx):
matchPixels=matchPixels+1
if matchPixels == perfectMatch:
print "Found L at position", tX
setColor(tPx,getColor(sPx))

i cant see if your functions works, everything it prints out just the file path, however, it is recommended using an array and create a list of letter inside

Related

Python docx - find and replace words with italicized version

I have thought of a few ways to accomplish this, but each is uglier than the next. I'm trying to think of a way to search for all instances of a word in a word document and italicize them.
I can't upload a word document, but here's what I had in mind:
A working example would find all instances of billybob, including the one in the table, and italicize them. The problem is the way the runs are frequently aligned means that one run might have billy and the next one might have bob so there's no straightforward way to find all of them.
I'm going to leave this open because the approach I came up with isn't perfect, but it works in the vast majority of the cases. Here is the code:
document = Document(<YOUR_DOC>)
# Data will be a list of rows represented as dictionaries
# containing each row's data.
characters = {}
for paragraph in <YOUR_PARAGRAPHS>:
run_string = ""
run_index = {}
i = 0
for x, run in enumerate(paragraph.runs):
# Create a string consisting of all the runs' text. Theoretically this
# should always be the same as parapgrah.text, but I didn't check
run_string = run_string + run.text
# The index i represents the starting position of the run in question
# within the string. We are creating a dictionary of form
# {<run_start_location>: <pointer_to_run>}
run_index[i] = x
# This will be the start of the next run
i = i + len(run.text)
word_you_wanted_to_find = re.findall("some_regex", paragraph.text)
for word in word_you_wanted_to_find:
# [m.start() for m in re.finditer(word, run_string)] returns the starting
# positions of each word that was found
for word_start in [m.start() for m in re.finditer(word, run_string)]:
word_end = word_start + len(word)
# This will be a list of the indices of the runs which have part
# of the word we want to include
included_runs = []
for key in run_index.keys():
# Remember, the key is the location in the string of the start of
# the run. In this case, the start of the word start should be less than
# the key+len(run) and the end of the word should be greater
# than the key (the start of the run)
if word_start <= (key + len(paragraph.runs[run_index[key]].text)) and key < word_end:
included_runs.append(key)
# If the key is larger than or equal to the end of the word,
# this means we have found all relevant keys. We don't need
# to loop over the rest (we could, it just wouldn't be efficient)
if key >= word_end:
break
# At this point, included_runs is a full list of indices to the relevant
# runs so we can modify each one in turn.
for run_key in included_runs:
paragraph.runs[run_index[run_key]].italic = True
document.save(<MODIFIED_DOC>)
Problem 1
The problem with this approach is that, while uncommon (at least in my doc), it is possible for a single run to contain more than just your target word. So you might end up italicizing an entire run that includes your run and then some. For my use case it didn't make sense to fix that problem here.
Solution
If you were to perfect what I did above you would have to change this code block:
if word_start <= (key + len(paragraph.runs[run_index[key]].text)) and key < word_end:
included_runs.append(key)
Here you have identified the run that has your word. You would need to extend the code to separate the word into its own run and remove it from the current run. Then you could separately italicize that run.
Problem 2
The code shown above doesn't handle both the table and normal text. I didn't need to for my use case, but in the general case you would have to check both.

How to manipulate 2d lists

I need help with working in 2d lists for my computing GCSE NEA(non examined assessment) and what I need to do is show the first letter of each song title on one line(One single song) along with the artists name for example AC/DC 'Back in Black' would be 'B i B' AC/DC
I am generally stuck on how to manipulate the array to show what I need and I've used several websites such as snakify and a few others
this is my program so far:
stageone=[['another one bites the dust','Queen',
'smoke on the water','Deep Purple',
'Stairway to heaven','Led Zeppelin',
'Carry on wayward son','Kansas',
'Don't stop believin','Journey']]
mainmenu=input("Welcome to the game please select an option-s for start the game,ts for top scores,ys for your scores,n for new game")
if mainmenu=='s':
play=input("do you want to continue you last game-c or do you want to start
a new game-n?")
if play=='s':
difficulty=input("What difficulty do you want to play? you can choose
from; easy,medium,difficult and legend")
if difficulty=='easy':
print("The easy mode of this game contains five stages,each with five
questions")
sure=input("Are you sure you want to play this gamemode?")
if sure=='y':
print(stageone)
I need the song to be on its own,not the whole array. And each song needs the first letter of each word not the whole word. I cannot figure out how to code this part of my program and help would greatly be appreciated. The song artist name however needs to be whole not single,first letter like the song title
when you define stageone, make it a list of lists like this:
stageone = [[title, band], [title, band], [title, band]]
then, instead of print(stageone) in the last line do:
for entry in stageone:
shortTitle = ' '.join([word[0] for word in entry[0].split(' ')])
print(shortTitle, entry[1])
Update: To get one hint at a time you'll need some method to select an entry out of stage one (for a game, I imagine this might be a random index). Then you just remove the for loop I gave before and use your selected entry like so
i = #some code to select an entry in stageone
entry = stageone[i]
shortTitle = ' '.join([word[0] for word in entry[0].split(' ')])
print(shortTitle, entry[1])
Note that there are a bunch of ways to make this more compact, but the original question makes me think a more verbose answer is better than a minimal solution. For instance, #calestini commented a one-liner to replace the for loop in my first response,
res = [[' '.join([x[0] for x in i[0].split()]), i[1]] for i in stageone ]
That's a fine solution - res will be a list like [[song hint, band name], [song hint, band name]] and then you print hints however you want. I'm not changing my original answer because I prefer not to use two list comprehensions in one line (I have a hard time reading the code).

Python issue with replace statement?

I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs.
def Manip(Strng):
#Strng = 'jayjay'
print (Strng.replace('j','h',1))
#Displays: 'hayjay'
print (Strng.replace('j','h',4))
#Displays: 'hayhay'
return
def Add_nums(Strng):
Size=len(str(Strng))
Total_per = str(Strng).count('%')
# Get The % Spots Position, So they only get replaced with numbers during permutation
currnt_Pos = 0
per = [] # % position per for percent
rGen = ''
for i in str(Strng):
if i == str('%'):
per.append(currnt_Pos)
currnt_Pos+=1
for num,pos in zip(str(self.ints),per):
rGen = Strng.replace(str(Strng[pos]),str(num),4);
return rGen
for pos in AlphaB: # DataBase Of The Positions Of Alphabets
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter,int(pos)))
# Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums
# And use the permutations function to generate other passwrds and then
# continue to the rest of this for loop which will generate something like cat222 or cat333
Add_nums(GenPass) # The Function That will add numbers to the Cat%%%
print (rGen);exit()

How to delay blits being iterated from a list

I'm trying to create a typewriter effect for text being blitted. By typewriter effect, I simply mean that Im trying to avoid the entirety of the text being blitted on screen at once. Instead, im trying to have each letter appear individually, with a slight delay before the next character in the string appears.
The catch is that im not using pygame's font.render. Instead, i've made my own custom fonts, each letter being saved as a separate image file. Now each alphanumeric character has it's own variable to which it's image is attached and each is appended to a list.
e.g:
letter_IMGs = []
a = "a" == pygame.image.load("IMG/letter_a.gif)
letter_IMG.append(a)
Lower, I have something along these lines:
letter_pos_x = 0
text = "Hello"
for i, c in enumerate(text):
screen.blit(letter_IMGs[i], (letter_pos_x,0))
letter_pos_x += 20
scroll_wait #this is a clock.delay variable. It's value was set outside the loop. I'm just calling it here.
Now as you'd guess, the result with that code is that the entire line of text appears simultaneously after the delay. I've been trying to code it as needed from there, but most of what I come up with returns with a "cannot iterate through surface objects" error.
I'm pretty much at a loss on how I should proceed next. Note that, ive been learning a bit of code on my own, on and off, for the past year and that I don't really know what im doing yet. Any and all help will be much appreciated.
Thanks in advance for your time.
Without getting into the pygame specifices too much, you just need to change the iterator so it returns substrings rather than letters:
def iterate_text(text):
for r in range(len(text)):
yield text[:r + 1]
which will return the substring iteratively:
for t in iterate_text('hello'):
print t
# h
# he
# hel
# hell
# hello
use a separate function to draw the string:
def draw_text(x, y, text):
characters = [letter_IMGs[t] for t in text]
cursor = x
for char in characters:
screen.blit(char, cursor, y)
cursor += 20
in your main loop you can decide when to get the next character. You'll basically do something like:
typewriter = iter_text('hello world')
text_to_draw = None
advance_text = False
at a level outside the loop that survive from frame to frame. When you want to draw the next character, you set advance_text to True, in and in the main loop:
if typewriter and advance_text:
text_to_draw = typewriter.next()
advance_text = False # until you set it again
if text_to_draw :
draw_text(0,0, draw_text)
You can start over by resetting the typewriter with new text, and control the timing of the new character appearing by setting advance_text to True before the next frame

How to check if variable matches, then do something

I have a script that pulls some data from a network device, strips off some crap and returns a value via a re.search.
the end result is i have two variables that contain a numerical value, say file1 contains one line with '10', file2 contains one line with '20'. i've put these into variables
oldnumber = 10
newnumber = 20
what i need to do is check to see if the numbers are the same value. if the numbers are the same, do nothing. if they aren't the same, then do something else - ie. send a mail to myself (smtplib works for me).
i'm new to python and finding my way, not sure how to code this?
i suppose the simplest way to describe this is if oldnumber = newnumber, then send mail, else do nothing.
If I remember well you're right
just do
if oldnumber!=newnumber;
do what you want
http://www.tutorialspoint.com/python/python_if_else.htm
almost right.
if oldnumber != newnumber:
# do something
# and then proceed..
Or:
if oldnumber == newnumber:
# do this
else:
# do that
# and then proceed..

Categories