Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions me/kmom06/analyzer/analyzer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""
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

# 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 count, word in words_sorted_by_count_then_alphabetically[: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]]
3 changes: 3 additions & 0 deletions me/kmom06/analyzer/lorum.txt
Original file line number Diff line number Diff line change
@@ -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.
77 changes: 77 additions & 0 deletions me/kmom06/analyzer/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""
A simple program to analyze text
"""
import analyzer

def main():
"""Main function of the analyzer program."""
current_file = "phil.txt"
#current_file = "lorum.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()
17 changes: 17 additions & 0 deletions me/kmom06/analyzer/phil.txt
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions me/kmom06/file/items.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
cookie
cake
tea
20 changes: 20 additions & 0 deletions me/kmom06/file/list_file.py
Original file line number Diff line number Diff line change
@@ -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)
92 changes: 92 additions & 0 deletions me/kmom06/file/string_file.py
Original file line number Diff line number Diff line change
@@ -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())
26 changes: 26 additions & 0 deletions me/kmom06/lab6/.answer.json
Original file line number Diff line number Diff line change
@@ -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 "
}
}
Loading