Using python an no other libraries, write a script that takes a file like: 'dataset.txt' and returns a list of all the words encountered. Special characters like whitespaces or punctuation should be the delimiter between tokens, but they should be kept at the end of the word Except for the newline character. It should be removed. Words of length 0 or 1 should be discarded. Then deduplicate those words and sort them by frequency. Print the first 10 words, their length and frequency. The python code will be ran inside of a google colab notebook.
Assistant
Certainly! Below is a Python script that accomplishes the task you described. This script reads a file named dataset.txt, processes the text to extract words based on your specifications, deduplicates them, sorts them by frequency, and then prints the top 10 words along with their lengths and frequencies.
Steps Overview:
Read the File: Open and read the contents of dataset.txt.
Tokenization: Split the text into words using whitespace and punctuation as delimiters. Punctuation at the end of words is retained, except for newline characters which are removed.
Filter Words: Discard words that are of length 0 or 1.
Deduplicate and Count Frequencies: Count the frequency of each unique word.
Sort and Display: Sort the words by frequency in descending order and display the top 10 words along with their lengths and frequencies.
Python Script:
python
# Define the set of punctuation characters
PUNCTUATIONS = set('!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
def is_punctuation(char):
return char in PUNCTUATIONS
def tokenize(text):
words = []
current_word = []
for char in text:
if char == '\n':
# Newline characters are removed
if current_word:
words.append(''.join(current_word))
current_word = []
continue
if char.isspace() or is_punctuation(char):
if current_word:
if is_punctuation(char):
# Append punctuation to the current word
current_word.append(char)
# Add the word to the list
word = ''.join(current_word)
words.append(word)
current_word = []
# If the delimiter is punctuation, and we just appended it, do nothing
# Else, continue to next character
else:
# Regular character, add to current word
current_word.append(char)
# Add the last word if exists
if current_word:
word = ''.join(current_word)
words.append(word)
return words
def main():
# Dictionary to hold word frequencies
word_freq = {}
try:
with open('dataset.txt', 'r', encoding='utf-8') as file:
for line in file:
# Remove newline characters
line = line.replace('\n', '')
# Tokenize the line
tokens = tokenize(line)
for token in tokens:
# Discard words of length 0 or 1
if len(token) <= 1:
continue
# Update frequency
if token in word_freq:
word_freq[token] += 1
else:
word_freq[token] = 1
except FileNotFoundError:
print("Error: 'dataset.txt' not found.")
return
# Sort the words by frequency in descending order
sorted_words = sorted(word_freq.items(), key=lambda item: item[1], reverse=True)
# Get the top 10 words
top_10 = sorted_words[:10]
# Print the results
print(f"{'Word':<20}{'Length':<10}{'Frequency':<10}")
print("-" * 40)
for word, freq in top_10:
print(f"{word:<20}{len(word):<10}{freq:<10}")
if __name__ == "__main__":
main()
How to Use in Google Colab:
Upload dataset.txt:
Click on the folder icon on the left sidebar in Google Colab.
Click the upload icon and select your dataset.txt file.
Run the Script:
Copy and paste the above script into a new cell in your Colab notebook.
Execute the cell. It will process the dataset.txt file and output the top 10 words with their lengths and frequencies.
Sample Output:
code
Word Length Frequency
----------------------------------------
example 7 15
test. 5 12
Python 6 10
script, 7 9
data 4 8
word! 5 7
frequency 9 6
dataset.txt 10 5
function 8 4
tokenize 8 3
Note: The above output is just an example. Your actual output will depend on the contents of your dataset.txt file.
Explanation of the Script:
Punctuation Handling: The is_punctuation function checks if a character is a punctuation mark based on the defined PUNCTUATIONS set.
Tokenization Logic:
The tokenize function iterates over each character in the text.
It builds words by appending characters until it encounters a delimiter (whitespace or punctuation).
If the delimiter is a punctuation, it's appended to the current word before the word is added to the list.
Newline characters are skipped and do not appear in any word.
Frequency Counting:
As each word is identified, it's added to the word_freq dictionary with its corresponding count.
Words with length 0 or 1 are ignored.
Sorting and Display:
The words are sorted based on frequency in descending order.
The top 10 words are selected and printed in a formatted manner showing the word, its length, and its frequency.
This script provides a straightforward way to process and analyze text data directly within a Google Colab notebook without relying on external libraries.