ctrl_c_ctrl_v
ctrl_c_ctrl_v

Reputation: 19

Python: pylightxl: if the user input match the text in the row A of excel, replace it with the text in B and print it out

I want to make a Spanish translator in python, so I create it with the dictionary.

translate = input("input: ")

translate_dictionary = {
  "Hello": "Hola",
  "Goodbye": "adiós"
}
for english, spanish in translate_dictionary.items():
  translate = translate.replace(english, spanish)
print(translate)

I want to rewrite this by using pylightxl, and link it to the excel spreadsheet, if the user input match the text in the row A of excel, replace it with the text in B and print it out, this is my excel spreadsheet content:

A B
Hello Hola
Goodbye adiós

And this is the code I wrote, I want to make the excel file a dictionary, row A is the key and row B is the value, and I have totally no idea how can i do it:

import pylightxl as xl

translate = input("input: ")

db = xl.readxl(fn='translate_library.xlsx')
 
for english, spanish in str(db):
    translate = translate.replace(db.ws(ws='Sheet1').address(address='A1'), db.ws(ws='Sheet1').address(address='B1'))

print(translate)

Upvotes: 0

Views: 219

Answers (1)

Rodrigo Llanes
Rodrigo Llanes

Reputation: 640

Just iterate through the excel sheet rows, and add it to the dictionary, like this:

translate_dictionary = {}
db = xl.readxl(fn='translate_library.xlsx')
for row in db.ws(ws='Sheet1').rows:
    translate_dictionary[row[0]] = row[1]

This in your code, will look like:

import pylightxl as xl

translate_dictionary = {}
db = xl.readxl(fn='translate_library.xlsx')
for row in db.ws(ws='Sheet1').rows:
    translate_dictionary[row[0]] = row[1]

translate = input("input: ")
for english, spanish in translate_dictionary.items():
  translate = translate.replace(english, spanish)
print(translate)

Upvotes: 2

Related Questions