So... in this example, we will see how we can search in a txt file the information we want based on a keyword. There is a list of workers that do their job once a week. We want to know who worked on each day of the week as the list is not ordered in this way.
Here is the list in the txt file (called workday.txt). Save this list as a txt file with the name indicated. Then save the code in a file called searchingdays.py (or anything you like).
The list
Amoresano Pasqualina friday
Califano Caputo monday
Cavallo Matteo thursday
Cesareo Filomena wednesday
Cortazzo Annarita monday
De Vita Maurizio monday
Franco Ida friday
Imbriaco Angela monday
Iuliano Tiziana monday
Lenza Agresta wednesday
Mangia Fortunata friday
Marotta La Marca monday
Piciocchi Sara saturday
Rambaldi Annarita friday
Russo Ortensia monday
Sansone Marotta tuesday
Saturno Giovanni thursday
Starace Guglielmo saturday
The code
def goSearch(day):
with open("workday.txt",encoding="utf-8") as file:
print("On ",day,"worked:\n----------------")
for line in file:
if day in line:
line = line.replace("\n","")
print(line.replace(day,""))
print()
week = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
for day in week:
goSearch(day)
'''
Line by line explanation
1 definition of the function to search ...
2 file object is created with open function
3 for every line in the txt fil
4 if there is the day (ex: the word monday) in that line
5 I replace the \n so that it does not print an empty line
6 it prints at the console the name of people working in that day without the day
7 an empty line for better visualisation
8
9 a list of the days of the week
10
11
12 a for loop that iterates the list of the day of the week
13 for every day it does the goSearch function described in 1-7 lines
'''
------------- HERE IS THE OUTPUT ----------------------
On monday worked:
----------------
Califano Caputo
Cortazzo Annarita
De Vita Maurizio
Imbriaco Angela
Iuliano Tiziana
Marotta La Marca
Russo Ortensia
On tuesday worked:
----------------
Sansone Marotta
On wednesday worked:
----------------
Cesareo Filomena
Lenza Agresta
On thursday worked:
----------------
Cavallo Matteo
Saturno Giovanni
On friday worked:
----------------
Amoresano Pasqualina
Franco Ida
Mangia Fortunata
Rambaldi Annarita
On saturday worked:
----------------
Piciocchi Sara
Starace Guglielmo
On sunday worked:
----------------
Comments
Post a Comment