import random
word_list = ["elma", "armut","kalem"]
chosen_word = random.choice(word_list)
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
map_1 = []
count = 0
end = False
for x in range(len(chosen_word)):
map_1.append("_")
if "_" not in map_1:
end = True
Print("YOU WON")
if count == 6 and "_" in map_1:
print("YOU LOST")
end = True
while end == False:
guess = input("Guess a letter ").lower()
count += 1
print(stages[- count])
for letter in chosen_word:
if guess == letter:
a = chosen_word.index(letter)
map_1[a] = guess
print(map_1)
else:
continue
print(map_1)
it does not stop when you guess all the letters,
it gives IndexError: list index out of range every time ı execute the program,I didn't write a part for what happens when you make a wrong guess now ı do the correct guess every time but still it ends like this.I just started the learn in this part ı am stuck ı don't know how to solve this.
you need to move the conditions into the while loop, otherwise, the program doesn't skip the while loop (end always is False).
while end == False:
guess = input("Guess a letter ").lower()
count += 1
print(stages[- count])
for letter in chosen_word:
if guess == letter:
a = chosen_word.index(letter)
map_1[a] = guess
print(map_1)
else:
continue
//end for loop
if "_" not in map_1:
end = True
print("YOU WON")
if count == 6 and "_" in map_1:
print("YOU LOST")
end = True
This is a part of a game TicTacToe. Both of them print a table of Tic Tac Toe, same output, but which one is better in algorithm and code quality? Is there anything can be modify to make it better?
#self.board is a list contains value of this table.
# e.g. an empty board should look like this:
# 0 1 2
# 0 | |
# -----------
# 1 | |
# -----------
# 2 | |
# code 1
printFormat = "\n 0 1 2 \n0 {} | {} | {} \n -----------\n1 {} | {} | {} \n -----------\n2 {} | {} | {} "
print(printFormat.format(*self.board[0],*self.board[1],*self.board[2]))
# code 2
printList = []
txtFormat ="{:} {:^3}"+"|{:^3}"*(self.size-1)
titleFormat = "{:^3} " * self.size
numbers = range(self.size)
line1 = "\n "+titleFormat.format(*numbers)
printList.append(line1)
for i in range(self.size):
contentLine = txtFormat.format(numbers[i],*self.board[i])
printList.append(contentLine)
cutOffLine = " "+"-"*(4*self.size-1)
printList.append(cutOffLine)
printList.pop()
for item in printList:
print(item)
I have a .txt file as in the example reported below. I would like to convert it into a .csv table, but I'm not having much success.
Mack3 Line Item Journal Time 14:22:33 Date 03.10.2015
Panteni Ledger 1L TGEPIO00/CANTINAOAS Page 20.001
--------------------------------------------------------------------------------------------------------------------------------------------
| Pstng Date|Entry Date|DocumentNo|Itm|Doc..Date |BusA|PK|SG|Sl|Account |User Name |LCurr| Amount in LC|Tx|Assignment |S|
|------------------------------------------------------------------------------------------------------------------------------------------|
| 07.01.2014|07.02.2014|4919005298| 36|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 0,85 | |20140107 | |
| 07.01.2014|07.02.2014|4919065298| 29|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 2,53 | |20140107 | |
| 07.01.2014|07.02.2014|4919235298| 30|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 30,00 | |20140107 | |
| 07.01.2014|07.02.2014|4119005298| 32|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 1,00 | |20140107 | |
| 07.01.2014|07.02.2014|9019005298| 34|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 11,10 | |20140107 | |
|------------------------------------------------------------------------------------------------------------------------------------------|
The file in question is structure as a report from SAP. Practicing with python and looking in other posts I found this code:
with open('file.txt', 'rb') as f_input:
for line in filter(lambda x: len(x) > 2 and x[0] == '|' and x[1].isalpha(), f_input):
header = [cols.strip() for cols in next(csv.reader(StringIO(line), delimiter='|', skipinitialspace=True))][1:-1]
break
with open('file.txt', 'rb') as f_input, open(str(ii + 1) + 'output.csv', 'wb') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(header)
for line in filter(lambda x: len(x) > 2 and x[0] == '|' and x[1] != '-' and not x[1].isalpha(), f_input):
csv_input = csv.reader(StringIO(line), delimiter='|', skipinitialspace=True)
csv_output.writerow(csv_input)
Unfortunately it does not work for my case. In fact it creates empty .csv files and it seems to not read properly the csv_input.
Any possible solution?
Your input file can be treated as CSV once we filter out a few lines, namely the ones that do not start with a pipe symbol '|' followed by a space ' ', which would leave us with this:
| Pstng Date|Entry Date|DocumentNo|Itm|Doc..Date |BusA|PK|SG|Sl|Account |User Name |LCurr| Amount in LC|Tx|Assignment |S|
| 07.01.2014|07.02.2014|4919005298| 36|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 0,85 | |20140107 | |
| 07.01.2014|07.02.2014|4919065298| 29|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 2,53 | |20140107 | |
| 07.01.2014|07.02.2014|4919235298| 30|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 30,00 | |20140107 | |
| 07.01.2014|07.02.2014|4119005298| 32|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 1,00 | |20140107 | |
| 07.01.2014|07.02.2014|9019005298| 34|07.01.2019| |81| | |60532640 |tARFooWMOND |EUR | 11,10 | |20140107 | |
Your output is mainly empty because that x[1].isalpha() check is never true on this data. The character in position 1 on each line is always a space, never alphabetic.
It's not necessary to open the input file multiple times, we can read, filter and write to the output in one go:
import csv
ii = 0
with open('file.txt', 'r', encoding='utf8', newline='') as f_input, \
open(str(ii + 1) + 'output.csv', 'w', encoding='utf8', newline='') as f_output:
input_lines = filter(lambda x: len(x) > 2 and x[0] == '|' and x[1] == ' ', f_input)
csv_input = csv.reader(input_lines, delimiter='|')
csv_output = csv.writer(f_output)
for row in csv_input:
csv_output.writerow(col.strip() for col in row[1:-1])
Notes:
You should not use binary mode when reading text files. Use r and w modes, respectively, and explicitly declare the file encoding. Choose the encoding that is the right one for your files.
For work with the csv module, open files with newline='' (which lets the csv module pick the correct line endings)
You can wrap multiple files in the with statements using the \ at the end of the line.
StringIO is completely unnecesary.
I'm not using skipinitialspace=True because some of the columns also have spaces at the end. Therefore I'm calling .strip() manually on each value when writing the row.
The [1:-1] is necessary to get rid of the superfluous empty columns (before the first and after the last | in the input)
Output is as follows
Pstng Date,Entry Date,DocumentNo,Itm,Doc..Date,BusA,PK,SG,Sl,Account,User Name,LCurr,Amount in LC,Tx,Assignment,S
07.01.2014,07.02.2014,4919005298,36,07.01.2019,,81,,,60532640,tARFooWMOND,EUR,"0,85",,20140107,
07.01.2014,07.02.2014,4919065298,29,07.01.2019,,81,,,60532640,tARFooWMOND,EUR,"2,53",,20140107,
07.01.2014,07.02.2014,4919235298,30,07.01.2019,,81,,,60532640,tARFooWMOND,EUR,"30,00",,20140107,
07.01.2014,07.02.2014,4119005298,32,07.01.2019,,81,,,60532640,tARFooWMOND,EUR,"1,00",,20140107,
07.01.2014,07.02.2014,9019005298,34,07.01.2019,,81,,,60532640,tARFooWMOND,EUR,"11,10",,20140107,
How to convert an image from one shape to other using thin plate spline in opencv python3. in c++ we have shape transformer class. in opencv python3 how can we implement it.
Thin plate spline indeed exists for opencv in python3.
You can use help function to get more info on which functions exist and how to use them like this:
>>> help(cv2.createThinPlateSplineShapeTransformer()) ## () braces matter !!
Help on ThinPlateSplineShapeTransformer object:
class ThinPlateSplineShapeTransformer(ShapeTransformer)
| Method resolution order:
| ThinPlateSplineShapeTransformer
| ShapeTransformer
| Algorithm
| builtins.object
|
| Methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate
signature.
|
| __repr__(self, /)
| Return repr(self).
|
| getRegularizationParameter(...)
| getRegularizationParameter() -> retval
|
| setRegularizationParameter(...)
| setRegularizationParameter(beta) -> None
|
| ----------------------------------------------------------------------
| Methods inherited from ShapeTransformer:
|
| applyTransformation(...)
| applyTransformation(input[, output]) -> retval, output
|
| estimateTransformation(...)
| estimateTransformation(transformingShape, targetShape, matches) ->
None
|
| warpImage(...)
| warpImage(transformingImage[, output[, flags[, borderMode[,
borderValue]]]]) -> output
|
| ----------------------------------------------------------------------
| Methods inherited from Algorithm:
|
| clear(...)
| clear() -> None
|
| getDefaultName(...)
| getDefaultName() -> retval
|
| save(...)
| save(filename) -> None
Source
Here's a shortened version of my code. Basically, I have a dictionary that stores a list that contains my ascii letter. I am prompting the user for a choice of letters to then be printed out with the special design. The second user input is used to decide how to print the letters. 'h' = horizontal and 'v' = vertical. The vertical section works perfectly. The horizontal does not.
def print_banner(input_string, direction):
'''
Function declares a list of ascii characters, and arranges the characters in order to be printed.
'''
ascii_letter = {'a': [" _______ ",
"( ___ )",
"| ( ) |",
"| (___) |",
"| ___ |",
"| ( ) |",
"| ) ( |",
"|/ \|"]}
# Branch that encompasses the horizontal banner
if direction == "h":
# Letters are 8 lines tall
for i in range(8):
for letter in range(len(input_string)):
# Dict[LetterIndex[ListIndex]][Line]
print(ascii_letter[input_string[letter]][i], end=" ")
print(" ")
# Branch that encompasses the vertical banner
elif direction == "v":
for letter in input_string:
for item in ascii_letter[letter]:
print(item)
def main():
user_input = input("Enter a word to convert it to ascii: ").lower()
user_direction = input("Enter a direction to display: ").lower()
print_banner(user_input, user_direction)
# This is my desired output if input is aa
_______ _______
( ___ ) ( ___ )
| ( ) | | ( ) |
| (___) | | (___) |
| ___ | | ___ |
| ( ) | | ( ) |
| ) ( | | ) ( |
|/ \| |/ \|
#What i get instead is:
_______
_______
( ___ )
( ___ )
| ( ) |
| ( ) |
| (___) |
| (___) |
| ___ |
| ___ |
| ( ) |
| ( ) |
| ) ( |
| ) ( |
|/ \|
|/ \|
You could zip the lines together and then join them:
if direction == "h":
zipped = zip(*(ascii_letter[char] for char in input_string))
for line in zipped:
print(' '.join(line))
Or just with the index:
if direction == "h":
for i in range(8):
for char in input_string:
print(ascii_letter[char][i], end=' ')
print()