From 7171a0342a15c78f5d63d4c2d2619b4681808b8b Mon Sep 17 00:00:00 2001 From: vtepliuk <82171003+vtepliuk@users.noreply.github.com> Date: Thu, 7 Nov 2024 22:50:30 +0100 Subject: [PATCH 1/3] Mina filer fran labb 6 med Python --- me/kmom06/analyzer/analyzer.py | 71 ++++++++++ me/kmom06/analyzer/lorum.txt | 3 + me/kmom06/analyzer/main.py | 76 +++++++++++ me/kmom06/analyzer/phil.txt | 17 +++ me/kmom06/file/items.txt | 3 + me/kmom06/file/list_file.py | 20 +++ me/kmom06/file/string_file.py | 92 +++++++++++++ me/kmom06/lab6/.answer.json | 26 ++++ me/kmom06/lab6/answer.py | 223 ++++++++++++++++++++++++++++++++ me/kmom06/lab6/dbwebb.py | 169 ++++++++++++++++++++++++ me/kmom06/lab6/instruction.html | 172 ++++++++++++++++++++++++ me/kmom06/lab6/newPasswords.txt | 0 me/kmom06/lab6/newQuotes.txt | 11 ++ me/kmom06/lab6/passwords.txt | 124 ++++++++++++++++++ me/kmom06/lab6/quotes.txt | 15 +++ 15 files changed, 1022 insertions(+) create mode 100644 me/kmom06/analyzer/analyzer.py create mode 100644 me/kmom06/analyzer/lorum.txt create mode 100644 me/kmom06/analyzer/main.py create mode 100644 me/kmom06/analyzer/phil.txt create mode 100644 me/kmom06/file/items.txt create mode 100644 me/kmom06/file/list_file.py create mode 100644 me/kmom06/file/string_file.py create mode 100644 me/kmom06/lab6/.answer.json create mode 100755 me/kmom06/lab6/answer.py create mode 100644 me/kmom06/lab6/dbwebb.py create mode 100644 me/kmom06/lab6/instruction.html create mode 100644 me/kmom06/lab6/newPasswords.txt create mode 100644 me/kmom06/lab6/newQuotes.txt create mode 100644 me/kmom06/lab6/passwords.txt create mode 100644 me/kmom06/lab6/quotes.txt diff --git a/me/kmom06/analyzer/analyzer.py b/me/kmom06/analyzer/analyzer.py new file mode 100644 index 0000000..79b4e3a --- /dev/null +++ b/me/kmom06/analyzer/analyzer.py @@ -0,0 +1,71 @@ +""" +Adding some functionalities for analyzer program +""" +def count_lines(text): + """ + Count amount of non-empty lines in a text. + """ + lines = text.split('\n') + not_empty_lines = [line for line in lines if line.strip() != ""] + return len(not_empty_lines) + +def count_words(text): + """ + Count amount of words in a text. + """ + words = text.split() + return len(words) + +def count_letters(text): + """ + Count amount of letters in a text. + """ + letters = [char for char in text if char.isalpha()] + return len(letters) + +def get_word_count(item): + """ + Sort words by frequency and alphabetically. + """ + return -item[1], item[0] + +def get_letter_count(item): + """ + Sort letters by frequency and alphabetically. + """ + return -item[1], item[0] + + +def word_frequency(text): + """ + Analyze word frequency. + """ + # Convert text to lowercase and remove punctuation manually + text = text.lower() + text = ''.join(char if char.isalnum() or char.isspace() else ' ' for char in text) + words = text.split() + word_count = {} + + for word in words: + word_count[word] = word_count.get(word, 0) + 1 + + # Sort by frequency first, then alphabetically from Z to A + sorted_word_count = sorted(word_count.items(), key=lambda item: (-item[1], item[0])) + total_words = len(words) + + return [(word, count, round((count / total_words) * 100, 1)) for word, count in sorted_word_count[:7]] + + +def letter_frequency(text): + """ + Analyze letter frequency. + """ + # Convert text to lowercase and remove non-alphabetic characters manually + text = text.lower() + letters = [char for char in text if char.isalpha()] + letter_count = {} + for letter in letters: + letter_count[letter] = letter_count.get(letter, 0) + 1 + sorted_letter_count = sorted(letter_count.items(), key=lambda item: (-item[1], item[0])) + total_letters = len(letters) + return [(letter, count, round((count / total_letters) * 100, 1)) for letter, count in sorted_letter_count[:7]] diff --git a/me/kmom06/analyzer/lorum.txt b/me/kmom06/analyzer/lorum.txt new file mode 100644 index 0000000..23cfe7a --- /dev/null +++ b/me/kmom06/analyzer/lorum.txt @@ -0,0 +1,3 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae aliquet dolor. +Vivamus neque dui, varius in iaculis a, imperdiet at ligula. +Donec dapibus urna. \ No newline at end of file diff --git a/me/kmom06/analyzer/main.py b/me/kmom06/analyzer/main.py new file mode 100644 index 0000000..024b459 --- /dev/null +++ b/me/kmom06/analyzer/main.py @@ -0,0 +1,76 @@ +""" +A simple program to analyze text +""" +import analyzer + +def main(): + """Main function of the analyzer program.""" + current_file = "phil.txt" + content = "" + + while True: + # Load content from the current file at the start of the loop + try: + with open(current_file, 'r') as file: + content = file.read() + print(f"Loaded content from {current_file}") + except FileNotFoundError: + print(f"File {current_file} not found.") + continue + + print("lines) Count lines") + print("words) Count words") + print("letters) Count letters") + print("word_frequency) Find 7 most used words") + print("letter_frequency) Find 7 most used letters") + print("all) Do everything") + print("change) Change file") + print("q) quit") + + choice = input("Enter command: ").strip().lower() + + if choice == "q": + break + + if choice == "change": + new_file = input("Enter the new file name (phil.txt or lorum.txt): ").strip() + try: + with open(new_file, 'r') as file: + content = file.read() # Read the new file's content immediately + current_file = new_file + print(f"File changed to {current_file}") + print(f"New content length: {len(content)}") + except FileNotFoundError: + print(f"File {new_file} not found. Please try again.") + continue + + # Debugging: Print the current file and content length + print(f"Current file: {current_file}") + print(f"Content length: {len(content)}") + + # Execute the chosen command + if choice == "lines": + print(analyzer.count_lines(content)) + elif choice == "words": + print(analyzer.count_words(content)) + elif choice == "letters": + print(analyzer.count_letters(content)) + elif choice == "word_frequency": + for word, count, percent in analyzer.word_frequency(content): + print(f"{word}: {count} | {percent}%") + elif choice == "letter_frequency": + for letter, count, percent in analyzer.letter_frequency(content): + print(f"{letter}: {count} | {percent}%") + elif choice == "all": + print(analyzer.count_lines(content)) + print(analyzer.count_words(content)) + print(analyzer.count_letters(content)) + for word, count, percent in analyzer.word_frequency(content): + print(f"{word}: {count} | {percent}%") + for letter, count, percent in analyzer.letter_frequency(content): + print(f"{letter}: {count} | {percent}%") + else: + print("Invalid command") + +if __name__ == "__main__": + main() diff --git a/me/kmom06/analyzer/phil.txt b/me/kmom06/analyzer/phil.txt new file mode 100644 index 0000000..a154996 --- /dev/null +++ b/me/kmom06/analyzer/phil.txt @@ -0,0 +1,17 @@ +Phil was quick to take a hint. He saw the menace in the shopkeepers +eyes, and, stopping abruptly, ran farther down the street, hugging his +fiddle, which he was afraid the angry tobacconist might seize and break. +This, to him, would be an irreparable misfortune and subject him to a +severe punishment, though the fault would not be his. +Next he strolled into a side street, and began to play in front of some +dwelling-houses. Two or three young children, who had been playing in +the street, gathered about him, and one of them gave him a penny. They +were clamorous for another tune, but Phil could not afford to work for +nothing, and, seeing no prospects of additional pay, took his violin, +and walked away, much to the regret of his young auditors, who, though +not rich, were appreciative. They followed him to the end of the block, +hoping that he would play again, but they were disappointed. +Phil played two or three times more, managing to obtain in all +twenty-five cents additional. He reached the corner of Thirteenth Street +just as the large public school, known as the Thirteenth Street School, +was dismissed for its noon intermission. \ No newline at end of file diff --git a/me/kmom06/file/items.txt b/me/kmom06/file/items.txt new file mode 100644 index 0000000..d2eb3df --- /dev/null +++ b/me/kmom06/file/items.txt @@ -0,0 +1,3 @@ +cookie +cake +tea \ No newline at end of file diff --git a/me/kmom06/file/list_file.py b/me/kmom06/file/list_file.py new file mode 100644 index 0000000..9a60ac6 --- /dev/null +++ b/me/kmom06/file/list_file.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +""" +Example of how to read the content of a file into a list +""" + +filename = "items.txt" + +with open(filename) as filehandle: + items_as_list = filehandle.readlines() +print(items_as_list) + + +items_as_list.append("cup") +print(items_as_list) + +list_as_str = ",".join(items_as_list) +print(list_as_str) + +with open(filename, "w") as filehandle: + filehandle.write(list_as_str) diff --git a/me/kmom06/file/string_file.py b/me/kmom06/file/string_file.py new file mode 100644 index 0000000..58d2678 --- /dev/null +++ b/me/kmom06/file/string_file.py @@ -0,0 +1,92 @@ + #!/usr/bin/env python3 +""" +Example of how to read and modify the content of a file +""" + +# the name of the file +filename = "items.txt" + +def menu(): + """ + Print available choices and return input + """ + print( + """ +1. Show file content +2. Add item, append +3. Replace content +4. Remove an item + """ + ) + return int(input("Choice: ")) + + + +def choice(inp): + """ + Check which action was chosen + """ + if inp == 1: + print(readfile()) + elif inp == 2: + write_to_file("\n" + input("Item to add: "), "a") + elif inp == 3: + replace_content() + elif inp == 4: + remove_item() + else: + exit() + + + +def readfile(): + """ + Read string from file + """ + with open(filename) as filehandle: + content = filehandle.read() + return content + + + +def write_to_file(content, mode): + """ + Write string to file + """ + with open(filename, mode) as filehandle: + filehandle.write(content) + + + +def replace_content(): + """ + Replace content of a file with new items + """ + item = "" + result = "" + while item != "q": + result += item + "\n" + item = input("Item to add: ") + write_to_file(result.strip(), "w") + + + +def remove_item(): + """ + Remove an item from the file + """ + content = readfile() + remove = input("What item should be removed: ") + + if remove in content: # check if item to remove exists + if content.index(remove) == 0: # if the item is the first line in the file + modified_content = content.replace(remove, "") + else: + modified_content = content.replace("\n" + remove, "") + write_to_file(modified_content.strip(), "w") + + + +if __name__ == "__main__": + while(True): + choice(menu()) diff --git a/me/kmom06/lab6/.answer.json b/me/kmom06/lab6/.answer.json new file mode 100644 index 0000000..49c3d66 --- /dev/null +++ b/me/kmom06/lab6/.answer.json @@ -0,0 +1,26 @@ +{ + "details": "Generated for vite24 at 2024-10-31 11:08:56.", + "key": "62e04dacb9496ffc2a18f79f48475fb5", + "summary": { + "questions": 6, + "points": 8, + "pass": 5.0, + "passdistinct": 8.0 + }, + "points": { + "1.1": 1, + "1.2": 1, + "1.3": 1, + "1.4": 1, + "1.5": 1, + "1.6": 3 + }, + "answers": { + "1.1": 649, + "1.2": "They are rare, much rarer than you think...", + "1.3": "Seize any opportunity, or anything that looks like opportunity.\nThey are rare, much rarer than you think...\n- Nassim Nicholas Taleb, \"The Black Swan\".\nThings which matter most must never be at the mercy of things which matter least.\n- Johann Wolfgang Von Goethe (1749-1832)\nI am replaced\nBut in practice, there is.\n- Albert Einstein\nWhen you have eliminated the impossible, whatever remains, however improbable, must be the truth.\n- Sherlock Holmes", + "1.4": "Seize any opportunity, or anything that looks like opportunity.\nThey are rare, much rarer than you think...\n- Nassim Nicholas Taleb, \"The Black Swan\".\nThings which matter most must never be at the mercy of things which matter least.\n- Johann Wolfgang Von Goethe (1749-1832)\nI am replaced\nBut in practice, there is.\n- Albert Einstein\nWhen you have eliminated the impossible, whatever remains, however improbable, must be the truth.\n- Sherlock Holmes\nAll creativity is an extended form of a joke.", + "1.5": "passwords.txt has 24 empty lines and contains: hYta234m\nL3VFxg9r\nrjJjHmHa\nQVrxsruu\neju7KdeW\nECtQHaZr\ncW3mgdm3\nwVNUmThW\n29YynXge\nwHG5svZV\nHKEPr8Hp\nWDwKgCs4\nDdk5wqCd\nVxtWBHka\nBsvAMJQ5\naeD5hcCQ\nfgSz5Ysz\nre4qYMxq\nVBDSJhtC\nHnwHjtZT\nhmdjare8\nSsFDeSFp\n4dGH6pWS\nKQPuSST2\nKAGH9bKu\nxS8B7gHH\natCggNy4\nuKu6yLbm\nL7BCbCpN\n92kj8P5S\nB3zjWUDp\nmtZGMrqb\nL9fca3tk\nYtvfs4se\nWj4MRq4G\nZucH4zMN\npsrDE2re\nBcuG7hB8\nnVQPmwdK\nkYD23RX9\nFp34PzMn\ns7f9vPGw\nGzrzF2mb\nbcAR8Ud9\nN8cjrZK8\nhYzHk4YH\nPzxPcHDT\nmnzaqG2q\ne622NFkK\nP5ZRTLZ3\nLPUe9FH2\n23wGs3tC\nxJB85s42\nFLXuxNbt\npNsn9X6C\nqzYHALBy\nxqmwCcV8\n2qZqJRcc\nD453PyFd\nMqjhNN5b\nRGHE7Z9N\nbVS6ZQbT\nQrZbQn8g\nHvTZpWFa\n9yXPfpqq\nDaEaT8Cp\njZcM63er\nHews9Sfh\nAzxPXUy6\ntB8A9UjL\nTHQM5gYH\nMghfN8Qv\nX4yPSxtC\nyLUXsRJ6\nYNHxk68V\nfDpNGCHj\ncPLb3rku\nEKdwNxUv\nnqQ95gGE\ns3n2Js4F\nb4wM4HEn\njEJc3vbt\n3B3jbUZa\nWc4y4XJh\nWZPrzn5d\n2CQqsCuE\n2WRXkv9d\nXECQa7hX\nphvhG4zB\nkpcJ6tRt\n54K3MwkL\nGL3EVUdf\nVLH5c9hJ\n7FLrxvhT\nv7aT26HT\ns29ufgKh\nzH49TvBJ\nDrsdk5HX\nhbrwUyTT\ngHuecwrB", + "1.6": "The file has 166 characters and the 9 first of the second row are: - Nassim " + } +} \ No newline at end of file diff --git a/me/kmom06/lab6/answer.py b/me/kmom06/lab6/answer.py new file mode 100755 index 0000000..6c32fe9 --- /dev/null +++ b/me/kmom06/lab6/answer.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 + +""" +62e04dacb9496ffc2a18f79f48475fb5 +python +lab6 +v4 +vite24 +2024-10-31 11:08:56 +v4.0.0 (2019-03-05) + +Generated 2024-10-31 12:08:57 by dbwebb lab-utility v4.0.0 (2019-03-05). +https://github.com/dbwebb-se/lab +""" + +from dbwebb import Dbwebb + +# pylint: disable=invalid-name + +dbwebb = Dbwebb() +dbwebb.ready_to_begin() + + + +# ========================================================================== +# Lab 6 - python +# +# During these exercises we train on reading, writing and appending data to +# text file's. +# + + + +# -------------------------------------------------------------------------- +# Section 1. Files +# +# +# + + + +# """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +# Exercise 1.1 (1 points) +# +# Read the `quotes.txt` -file in UTF-8 encoding and store the content into a +# variable. Answer with the number of characters in the file. +# +# Write your code below and put the answer into the variable ANSWER. +# +file_name = "quotes.txt" + +def readfile(): + with open(file_name) as filehandle: + content_of_file = filehandle.read() + return content_of_file + +content = readfile() + +ANSWER = len(content) + +# I will now test your answer - change false to true to get a hint. +dbwebb.assert_equal("1.1", ANSWER, False) + +# """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +# Exercise 1.2 (1 points) +# +# Use your variable from the exercise above and answer with the contents on +# line number 2. You should not have a newline at the end of the line. +# +# Write your code below and put the answer into the variable ANSWER. +# + +def readfile(): + with open(file_name) as filehandle: + content_of_file = filehandle.read() + return content_of_file + +content = readfile() +lines = content.split('\n') + + + + + +ANSWER = lines[1] + +# I will now test your answer - change false to true to get a hint. +dbwebb.assert_equal("1.2", ANSWER, False) + +# """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +# Exercise 1.3 (1 points) +# +# First, read the content inside of quotes.txt and remove the 5 last rows. +# Then replace line number 6 with the new string "I am replaced". +# Then, create a new file called `newQuotes.txt` where you save the new +# changes. Replace `newQuotes.txt` if it already exists. +# +# Answer with the new content inside `newQuotes.txt`. Don't have a "\n" on +# the last line. +# +# Write your code below and put the answer into the variable ANSWER. +# +new_file_name = "newQuotes.txt" + +def readfile(): + with open(file_name) as filehandle: + content_of_file = filehandle.read() + return content_of_file + +content = readfile() +lines = content.split('\n') +lines = lines[:-5] +lines[5] = "I am replaced" +new_content = '\n'.join(lines) +with open(new_file_name, 'w') as filehandle: + filehandle.write(new_content) +ANSWER = new_content + +# I will now test your answer - change false to true to get a hint. +dbwebb.assert_equal("1.3", ANSWER, False) + +# """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +# Exercise 1.4 (1 points) +# +# Append the following sentence on a new line at the end of newQuotes.txt and +# answer with the content. +# +# *"All creativity is an extended form of a joke."* +# +# Write your code below and put the answer into the variable ANSWER. +# +new_file_name = "newQuotes.txt" +with open(new_file_name, 'r') as filehandle: + content = filehandle.read() + +new_sentence = "All creativity is an extended form of a joke." +updated_file = content + '\n' + new_sentence + +with open(new_file_name, 'w') as filehandle: + filehandle.write(updated_file) + + + + + + +ANSWER = updated_file + +# I will now test your answer - change false to true to get a hint. +dbwebb.assert_equal("1.4", ANSWER, False) + +# """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +# Exercise 1.5 (1 points) +# +# Store the number of empty lines that `passwords.txt` has and create a new +# file called `newPasswords.txt` containing the lines that are not empty. +# +# Answer with the following: +# +# *passwords.txt has X empty lines and contains: Y* +# +# Replace `X` with the number of empty lines and `Y` with the new files +# content. +# +# Write your code below and put the answer into the variable ANSWER. +# +with open('passwords.txt', 'r') as filehandle: + lines = filehandle.readlines() +empty_lines_count = 0 +not_empty_lines = [] + +for line in lines: + if line.strip() == "": + empty_lines_count += 1 + else: + not_empty_lines.append(line.strip()) +with open('newPasswords.txt', 'w') as filehandle: + new_file_content = '\n'.join(not_empty_lines) +result = f"passwords.txt has {empty_lines_count} empty lines and contains: {new_file_content}" + + + + + + +ANSWER = result + +# I will now test your answer - change false to true to get a hint. +dbwebb.assert_equal("1.5", ANSWER, False) + +# """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +# Exercise 1.6 (3 points) +# +# Write the content of line numbers 2, 3 and 4 from `quotes.txt` to a new +# file that you create called `extraQuotes.txt`. Replace `extraQuotes.txt` if +# it already exists. +# Save the total number of characters and the 9 first characters of the +# second line into variables. +# +# Answer with the following string: +# "The file has X characters and the 9 first of the second row are: Y" +# +# **Example**: +# *"The file has 220 characters and the 9 first of the second row are: - Jon +# Doe"* +# +# Do not include newlines when you count the number of characters. +# +# Write your code below and put the answer into the variable ANSWER. +# + + + + + + +ANSWER = "Replace this text with the variable holding the answer." + +# I will now test your answer - change false to true to get a hint. +dbwebb.assert_equal("1.6", ANSWER, False) + + +dbwebb.exit_with_summary() diff --git a/me/kmom06/lab6/dbwebb.py b/me/kmom06/lab6/dbwebb.py new file mode 100644 index 0000000..8b10b02 --- /dev/null +++ b/me/kmom06/lab6/dbwebb.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 + +""" +Python dbwebb module for asserting and auto correcting labs. + +It reads the answers from a json-file and use it +for checking with assert_equal(). +""" + +import json +import sys +import os + + +class Dbwebb(): + """ + Class for autocorrecting labs. + """ + + # Texts + _text = { + "prompt": ">>> ", + + "ready": "{prompt} Ready to begin.", + + "default": "Replace this text with the variable holding the answer.", + + "no_answer": "{prompt} {question} NOT YET DONE.", + + "correct": """{prompt} {question} CORRECT. Well done!""", + + "fail": """{prompt} {question} FAIL. +{prompt} You said: +{answer} {type} +{prompt}""", + + "hint": """Hint: +{answer} {type}""", + + # pylint: disable=line-too-long + "done": """{prompt} Done with status {total}/{correct}/{failed}/{not_done} (Total/Correct/Failed/Not done).""", # noqa + + "pointspass": """{prompt} Points earned: {points}p of {total}p (PASS=>{passval}p).""", # noqa + + "pointspassdistinct": """{prompt} Points earned: {points}p of {total}p (PASS=>{passval}p PASS W DISTINCTION=>{passdistinct}p).""", # noqa + + "passdistinct": "\033[96m{prompt}Grade: PASS WITH DISTINCTION!!! :-D\033[0m", + "pass": "\033[92m{prompt}Grade: PASS! :-)\033[0m", + + # pylint: enable=line-too-long + "no_pass": "\033[93m{prompt}Grade: Thou Did Not Pass. :-|\033[0m" + } + + def __init__(self, answers_file_name=".answer.json"): + """ + Init by reading json-file with answers. + """ + location = os.path.realpath( + os.path.join( + os.getcwd(), + os.path.dirname(__file__) + ) + ) + with open(os.path.join(location, answers_file_name), encoding="utf8") as fd: + self.answers = json.load(fd) + self.correct = 0 + self.failed = 0 + self.not_done = 0 + self.points = 0 + self.prompt = self._text["prompt"] + + def ready_to_begin(self): + """ + Called before everything starts. + """ + print(self._text["ready"].format(prompt=self.prompt)) + + def assert_equal(self, question, answer, hint=False): + """ + Check if the answer is correct or not, present a hint if asked for. + """ + status = None + + if answer == self._text["default"]: + status = self._text["no_answer"].format( + prompt=self.prompt, + question=question + ) + self.not_done += 1 + + elif answer == self.answers["answers"][question]: + status = self._text["correct"].format( + prompt=self.prompt, + question=question + ) + self.correct += 1 + self.points += self.answers["points"][question] + + else: + status = self._text["fail"].format( + prompt=self.prompt, + question=question, + answer=answer, + type=str(type(answer)) + ) + + if hint: + status += self._text["hint"].format( + answer=self.answers["answers"][question], + type=str(type(self.answers["answers"][question])) + ) + + self.failed += 1 + + print(status) + + def exit_with_summary(self): + """ + Print a exit message with the result of all tests. + Exit with status 0 if all tasks are solved, else exit with status 1. + """ + questions = self.answers["summary"]["questions"] + points = self.answers["summary"]["points"] + pass_val = self.answers["summary"]["pass"] + pass_distinct = self.answers["summary"]["passdistinct"] + + print(self._text["done"].format( + prompt=self.prompt, + total=questions, + correct=self.correct, + failed=self.failed, + not_done=self.not_done + )) + + if pass_distinct: + print(self._text["pointspassdistinct"].format( + prompt=self.prompt, + points=self.points, + total=points, + passval=pass_val, + passdistinct=pass_distinct + )) + elif pass_val: + print(self._text["pointspass"].format( + prompt=self.prompt, + points=points, + total=questions, + passval=pass_val + )) + + + # Grading + did_pass = self.correct == questions + if pass_val: + did_pass = self.points >= pass_val + + did_pass_distinct = None + if pass_distinct: + did_pass_distinct = self.points >= pass_distinct + + if did_pass_distinct: + print(self._text["passdistinct"].format(prompt=self.prompt)) + sys.exit(0) + elif did_pass: + print(self._text["pass"].format(prompt=self.prompt)) + sys.exit(0) + else: + print(self._text["no_pass"].format(prompt=self.prompt)) + sys.exit(42) diff --git a/me/kmom06/lab6/instruction.html b/me/kmom06/lab6/instruction.html new file mode 100644 index 0000000..faac157 --- /dev/null +++ b/me/kmom06/lab6/instruction.html @@ -0,0 +1,172 @@ + + + + + Lab 6 - python + + + + +
+62e04dacb9496ffc2a18f79f48475fb5
+python
+lab6
+v4
+vite24
+2024-10-31 11:08:56
+v4.0.0 (2019-03-05)
+
+ +

Generated 2024-10-31 12:08:56 by dbwebb lab-utility v4.0.0 (2019-03-05).

+
+ +

Lab 6 - python

+

During these exercises we train on reading, writing and appending data to text file’s.

+ + +

1. Files

+ + + +

Exercise 1.1 (1 points)

+

Read the quotes.txt -file in UTF-8 encoding and store the content into a variable. Answer with the number of characters in the file.

+ + + + + + +

Exercise 1.2 (1 points)

+

Use your variable from the exercise above and answer with the contents on line number 2. You should not have a newline at the end of the line.

+ + + + + + +

Exercise 1.3 (1 points)

+

First, read the content inside of quotes.txt and remove the 5 last rows. Then replace line number 6 with the new string “I am replaced”. +Then, create a new file called newQuotes.txt where you save the new changes. Replace newQuotes.txt if it already exists.

+ +

Answer with the new content inside newQuotes.txt. Don’t have a “\n” on the last line.

+ + + + + + +

Exercise 1.4 (1 points)

+

Append the following sentence on a new line at the end of newQuotes.txt and answer with the content.

+ +

“All creativity is an extended form of a joke.”

+ + + + + + +

Exercise 1.5 (1 points)

+

Store the number of empty lines that passwords.txt has and create a new file called newPasswords.txt containing the lines that are not empty.

+ +

Answer with the following:

+ +

passwords.txt has X empty lines and contains: Y

+ +

Replace X with the number of empty lines and Y with the new files content.

+ + + + + + +

Exercise 1.6 (3 points)

+

Write the content of line numbers 2, 3 and 4 from quotes.txt to a new file that you create called extraQuotes.txt. Replace extraQuotes.txt if it already exists. +Save the total number of characters and the 9 first characters of the second line into variables.

+ +

Answer with the following string: +“The file has X characters and the 9 first of the second row are: Y”

+ +

Example: +“The file has 220 characters and the 9 first of the second row are: - Jon Doe”

+ +

Do not include newlines when you count the number of characters.

+ + + + + + + +
+62e04dacb9496ffc2a18f79f48475fb5 + + + diff --git a/me/kmom06/lab6/newPasswords.txt b/me/kmom06/lab6/newPasswords.txt new file mode 100644 index 0000000..e69de29 diff --git a/me/kmom06/lab6/newQuotes.txt b/me/kmom06/lab6/newQuotes.txt new file mode 100644 index 0000000..f613a5c --- /dev/null +++ b/me/kmom06/lab6/newQuotes.txt @@ -0,0 +1,11 @@ +Seize any opportunity, or anything that looks like opportunity. +They are rare, much rarer than you think... +- Nassim Nicholas Taleb, "The Black Swan". +Things which matter most must never be at the mercy of things which matter least. +- Johann Wolfgang Von Goethe (1749-1832) +I am replaced +But in practice, there is. +- Albert Einstein +When you have eliminated the impossible, whatever remains, however improbable, must be the truth. +- Sherlock Holmes +All creativity is an extended form of a joke. \ No newline at end of file diff --git a/me/kmom06/lab6/passwords.txt b/me/kmom06/lab6/passwords.txt new file mode 100644 index 0000000..03e80cc --- /dev/null +++ b/me/kmom06/lab6/passwords.txt @@ -0,0 +1,124 @@ +hYta234m +L3VFxg9r + + +rjJjHmHa +QVrxsruu +eju7KdeW + + + +ECtQHaZr +cW3mgdm3 +wVNUmThW +29YynXge +wHG5svZV +HKEPr8Hp +WDwKgCs4 + + +Ddk5wqCd +VxtWBHka +BsvAMJQ5 +aeD5hcCQ +fgSz5Ysz +re4qYMxq +VBDSJhtC + + + +HnwHjtZT +hmdjare8 +SsFDeSFp +4dGH6pWS +KQPuSST2 +KAGH9bKu +xS8B7gHH +atCggNy4 +uKu6yLbm + +L7BCbCpN +92kj8P5S +B3zjWUDp +mtZGMrqb +L9fca3tk +Ytvfs4se +Wj4MRq4G + + + +ZucH4zMN +psrDE2re +BcuG7hB8 +nVQPmwdK +kYD23RX9 +Fp34PzMn +s7f9vPGw +GzrzF2mb +bcAR8Ud9 +N8cjrZK8 +hYzHk4YH +PzxPcHDT +mnzaqG2q +e622NFkK +P5ZRTLZ3 + + + +LPUe9FH2 +23wGs3tC +xJB85s42 +FLXuxNbt +pNsn9X6C +qzYHALBy +xqmwCcV8 +2qZqJRcc +D453PyFd + +MqjhNN5b +RGHE7Z9N +bVS6ZQbT +QrZbQn8g +HvTZpWFa +9yXPfpqq +DaEaT8Cp +jZcM63er +Hews9Sfh +AzxPXUy6 +tB8A9UjL +THQM5gYH +MghfN8Qv +X4yPSxtC + + +yLUXsRJ6 +YNHxk68V +fDpNGCHj +cPLb3rku +EKdwNxUv +nqQ95gGE +s3n2Js4F +b4wM4HEn +jEJc3vbt +3B3jbUZa +Wc4y4XJh +WZPrzn5d +2CQqsCuE +2WRXkv9d +XECQa7hX +phvhG4zB +kpcJ6tRt + +54K3MwkL +GL3EVUdf +VLH5c9hJ +7FLrxvhT + +v7aT26HT +s29ufgKh +zH49TvBJ +Drsdk5HX + + +hbrwUyTT +gHuecwrB \ No newline at end of file diff --git a/me/kmom06/lab6/quotes.txt b/me/kmom06/lab6/quotes.txt new file mode 100644 index 0000000..fd6b402 --- /dev/null +++ b/me/kmom06/lab6/quotes.txt @@ -0,0 +1,15 @@ +Seize any opportunity, or anything that looks like opportunity. +They are rare, much rarer than you think... +- Nassim Nicholas Taleb, "The Black Swan". +Things which matter most must never be at the mercy of things which matter least. +- Johann Wolfgang Von Goethe (1749-1832) +In theory, there's no difference between theory and practice. +But in practice, there is. +- Albert Einstein +When you have eliminated the impossible, whatever remains, however improbable, must be the truth. +- Sherlock Holmes +I find that the harder I work, the more luck I seem to have. +- Thomas Jefferson +Lisp is a programmable programming language. +- John Foderaro +END OF FILE \ No newline at end of file From 42d42912fd4754ec6f83acc5e9e4337671bc7156 Mon Sep 17 00:00:00 2001 From: vtepliuk Date: Tue, 12 Nov 2024 11:48:31 +0100 Subject: [PATCH 2/3] En test-uppgift "1.6", kan man koda --- me/kmom06/lab6/answer.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/me/kmom06/lab6/answer.py b/me/kmom06/lab6/answer.py index 6c32fe9..51d1ec2 100755 --- a/me/kmom06/lab6/answer.py +++ b/me/kmom06/lab6/answer.py @@ -209,12 +209,24 @@ def readfile(): # Write your code below and put the answer into the variable ANSWER. # +with open('quotes.txt', 'r') as file_handle: + lines = file_handle.readlines() +lines_2_3_and_4 = [] +for line_number, line in enumerate(lines, 1): + if line_number in {2, 3, 4}: + lines_2_3_and_4.append(line) +assert len(lines_2_3_and_4) == 3 +with open('extraQuotes.txt', 'w') as file_handle: + file_handle.writelines(lines_2_3_and_4) +total_characters = sum(len(line) for line in lines_2_3_and_4) +line_2_first_9_chars = lines_2_3_and_4[1][:9] +result = f"The file has {total_characters} and the 9 first of the second row are {line_2_first_9_chars}" -ANSWER = "Replace this text with the variable holding the answer." +ANSWER = result # I will now test your answer - change false to true to get a hint. dbwebb.assert_equal("1.6", ANSWER, False) From 953a9c0df07eb9734eaacdcf29f0635ac7ee4025 Mon Sep 17 00:00:00 2001 From: vtepliuk Date: Tue, 12 Nov 2024 11:49:46 +0100 Subject: [PATCH 3/3] Labbat och debuggat lite med Analyzer-projektet :bug: --- me/kmom06/analyzer/analyzer.py | 25 ++++++++++++++++++++++--- me/kmom06/analyzer/main.py | 1 + 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/me/kmom06/analyzer/analyzer.py b/me/kmom06/analyzer/analyzer.py index 79b4e3a..91a4c88 100644 --- a/me/kmom06/analyzer/analyzer.py +++ b/me/kmom06/analyzer/analyzer.py @@ -49,11 +49,30 @@ def word_frequency(text): for word in words: word_count[word] = word_count.get(word, 0) + 1 - # Sort by frequency first, then alphabetically from Z to A - sorted_word_count = sorted(word_count.items(), key=lambda item: (-item[1], item[0])) + # Make something like `{ "word": count, ... }` into a list of tuples like `[(count, word), ...]` + word_counts = [(count, word) for (word, count) in word_count.items()] + print('debug! as is first 10: ', word_counts[:10]) # Check! + # + # # Sort by Count + # word_counts_sorted = sorted(word_counts, key=itemgetter(0), reverse=True)[:10] + # print('debug! sorted by count: ', word_counts_sorted) # Check! + # + # # Sort Alphabetically + # words_sorted = sorted(word_counts_sorted, key=itemgetter(1)) + # print('debug! sorted by word: ', words_sorted) # Check! + + # Sort by Count and then Alphabetically + def _my_custom_sort_function(sortable_thing): + """My special function to sort by count and then alphabetically""" + # print('debug! sortable_things (what is it?): ', sortable_thing) # Check! + return sortable_thing[0], sortable_thing[1] + + words_sorted_by_count_then_alphabetically = sorted(word_counts, key=_my_custom_sort_function, reverse=True) + print('debug! sorted by count then word: ', words_sorted_by_count_then_alphabetically[:10]) # Check! + total_words = len(words) - return [(word, count, round((count / total_words) * 100, 1)) for word, count in sorted_word_count[:7]] + return [(word, count, round((count / total_words) * 100, 1)) for count, word in words_sorted_by_count_then_alphabetically[:7]] def letter_frequency(text): diff --git a/me/kmom06/analyzer/main.py b/me/kmom06/analyzer/main.py index 024b459..f0ec75b 100644 --- a/me/kmom06/analyzer/main.py +++ b/me/kmom06/analyzer/main.py @@ -6,6 +6,7 @@ def main(): """Main function of the analyzer program.""" current_file = "phil.txt" + #current_file = "lorum.txt" content = "" while True: