##1
def get_freq(filename):
# Initialize an empty dictionary to store word frequencies
word_freq = {}
# Open the file in read mode
with open(filename, 'r') as file:
# Iterate through each line in the file
for line in file:
# Remove leading and trailing whitespaces and convert to lowercase
word = line.strip().lower()
# Check if the word is already in the dictionary
if word in word_freq:
# If yes, increment its frequency
word_freq[word] += 1
else:
# If not, add it to the dictionary with frequency 1
word_freq[word] = 1
# Return the dictionary containing word frequencies
return word_freq
##2
def relation(file1, file2):
# Open file1 and file2 in read mode
with open(file1, 'r') as f1, open(file2, 'r') as f2:
# Read all lines from file1 and file2
lines1 = f1.readlines()
lines2 = f2.readlines()
# Remove newline characters from each line
lines1_stripped = [line.strip() for line in lines1]
lines2_stripped = [line.strip() for line in lines2]
# Check if file1 is a subset of file2
if all(line1 == line2 for line1, line2 in zip(lines1_stripped,
lines2_stripped)):
return "Equal" if len(lines1_stripped) == len(lines2_stripped) else
"Subset"
# If none of the above conditions are satisfied, return "No Relation"
else:
return "No Relation"
##3
import csv
def get_goals(filename, country_name):
# Initialize variables to store the number of players and total goals
num_players = 0
num_goals = 0
# Open the CSV file
with open(filename, 'r', newline='') as csvfile:
# Create a CSV reader object
csv_reader = csv.reader(csvfile)
# Skip the header row
next(csv_reader)
# Iterate over each row in the CSV file
for row in csv_reader:
# Extract the country name and goals scored from the row
player_country = row[1]
player_goals = int(row[2])
# Check if the player's country matches the specified country name
if player_country == country_name:
# Increment the number of players from this country and add their
goals to the total
num_players += 1
num_goals += player_goals
# If no players from the specified country were found, return (-1, -1)
if num_players == 0:
return (-1, -1)
# Otherwise, return the tuple (num_players, num_goals)
return (num_players, num_goals)
##4
import csv
def num_to_words(matrix):
# Define a dictionary mapping digits to their corresponding words
num_words = {
0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four',
5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
}
# Open the file 'words.csv' for writing
with open('words.csv', 'w', newline='') as csvfile:
# Create a CSV writer object
csv_writer = csv.writer(csvfile)
# Write each row of the matrix to the CSV file
for row in matrix:
# Convert each digit to its corresponding word
word_row = [num_words[num] for num in row]
# Write the row to the CSV file
csv_writer.writerow(word_row)