saidhanush4422 / Helium-3

0 stars 1 forks source link

Module 1: Creating a function to take input #11

Closed saidhanush4422 closed 1 year ago

saidhanush4422 commented 1 year ago

Today, We have successfully completed the first phase of input collection

These are the test cases we have researched so far

Test Case 1:

write a python code to create an upload txt file button and read the data inside that file, line by line

from tkinter import *
from tkinter import filedialog

root = Tk()
root.geometry("300x200")

def upload_file():
    filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt"), ("All Files", "*.*")))
    with open(filename, "r") as f:
        for line in f:
            print(line.strip())

upload_button = Button(root, text="Upload File", command=upload_file)
upload_button.pack(pady=20)

root.mainloop()

This code creates a GUI window using the tkinter library. When the user clicks the "Upload File" button, it opens a file dialog that allows the user to select a text file. Once the user selects a file, the code reads the file and prints each line to the console.

Note: This is a basic code snippet and it can be further modified or extended to meet your specific requirements.

Test Case 2:

read the above collected data in a variable called text

from tkinter import *
from tkinter import filedialog

root = Tk()
root.geometry("300x200")

def upload_file():
    filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt"), ("All Files", "*.*")))
    with open(filename, "r") as f:
        text = f.read()
        print(text)

upload_button = Button(root, text="Upload File", command=upload_file)
upload_button.pack(pady=20)

root.mainloop()

In this modified code, we've added a line to read the entire contents of the file and store it in a variable called text. We can then use this variable to perform further operations on the data as required.

Test Case 3:

In the above code I want to call a function to each and every line of the data, how do i do that

from tkinter import *
from tkinter import filedialog

root = Tk()
root.geometry("300x200")

# Function to process each line of data
def process_line(line):
    # Perform operations on the line here
    print(line.upper())

def upload_file():
    filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt"), ("All Files", "*.*")))
    with open(filename, "r") as f:
        for line in f:
            process_line(line.strip())

upload_button = Button(root, text="Upload File", command=upload_file)
upload_button.pack(pady=20)

In this modified code, we've defined a new function called process_line that takes a single parameter line. This function can be customized to perform any operations you need on each line of the data.

Inside the upload_file function, we're looping through each line of the file and calling process_line with the current line as a parameter. We're also using the strip method to remove any whitespace characters from the beginning and end of each line.

You can replace the print(line.upper()) statement inside the process_line function with your own custom function call that performs the required operations on each line of the data.

Test Case 4:

Write a python code to delete the first 'n' number of elements of a uploaded txt file in each and every line and then read the data

from tkinter import *
from tkinter import filedialog

root = Tk()
root.geometry("300x200")

# Function to process each line of data
def process_line(line, n):
    # Delete the first n elements from the line
    modified_line = line.split()[n:]
    # Convert the modified line back to a string and return it
    return ' '.join(modified_line)

def delete_n_elements(n):
    filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt"), ("All Files", "*.*")))
    with open(filename, "r") as f:
        modified_lines = [process_line(line.strip(), n) for line in f]
    return modified_lines

# Example usage:
modified_data = delete_n_elements(3)
for line in modified_data:
    print(line)

root.mainloop()

In this code, we've defined a new function called process_line that takes two parameters: line and n. This function splits the line into a list of words, deletes the first n elements from the list, and then converts the modified list back into a string with a space between each word.

We've also defined a new function called delete_n_elements that takes a single parameter n. This function prompts the user to select a text file, reads each line of the file, and passes each line to the process_line function along with the value of n. The modified lines are stored in a list and returned.

Finally, we've demonstrated how to use the delete_n_elements function by calling it with an argument of 3 and then printing each modified line to the console.

You can modify the code to perform different operations on each line of the file as required.

Test Case 5:

return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 550: character maps to how do I resolve the above error

The error message indicates that there is a character in your input data that can't be decoded using the character map that's being used. Here are a few possible solutions to resolve this error:

Specify the correct encoding: Ensure that you're using the correct encoding to decode the input data. Common encodings are utf-8, ascii, and latin-1. Try specifying the encoding explicitly using the encoding parameter when reading the input data.

Ignore errors: You can also choose to ignore the error and continue decoding the rest of the data. To do this, you can pass the errors='ignore' parameter when decoding the data.

Replace errors: If ignoring errors is not an option, you can choose to replace any problematic characters with a replacement character. To do this, you can pass the errors='replace' parameter when decoding the data.

Use a different codec: Try using a different codec to decode the input data. The codecs module in Python provides a variety of codecs for encoding and decoding data. You can try using a different codec that's better suited to your input data.

Here's an example of how to specify the encoding explicitly when reading input data:

with open('filename.txt', 'r', encoding='utf-8') as f:
    data = f.read()

Here's an example of how to ignore errors when decoding data:

data = b'\x8dabc'
decoded_data = data.decode('utf-8', errors='ignore')
print(decoded_data)  # Output: 'abc'

Here's an example of how to replace errors when decoding data:

data = b'\x8dabc'
decoded_data = data.decode('utf-8', errors='replace')
print(decoded_data)  # Output: '?abc'

If none of these solutions work, you may need to inspect your input data to determine what encoding it was originally encoded in, or if there are any other issues with the data that need to be resolved.

Test Case 6:

I want to create an instance in python language where the user can choose whether to type in the command prompt or to upload a text file You can create an instance in Python where the user can choose whether to type in the command prompt or to upload a text file by using the input() and open() functions in Python. Here's an example:

user_input = input("Enter '1' to type input, '2' to upload a text file: ")

if user_input == '1':
    # Prompt user to type input in the command prompt
    user_text = input("Enter text: ")
elif user_input == '2':
    # Prompt user to upload a text file
    file_path = input("Enter file path: ")
    with open(file_path, 'r') as file:
        user_text = file.read()
else:
    print("Invalid input. Please enter '1' or '2'.")

# Do something with the user_text variable

In this example, the user is prompted to enter '1' to type input in the command prompt or '2' to upload a text file. If the user enters '1', the program prompts the user to enter text in the command prompt using the input() function. If the user enters '2', the program prompts the user to enter a file path, then reads the contents of the file using the open() function and the with statement. The contents of the file are then stored in the user_text variable.

You can modify this example to suit your needs, such as adding error handling for invalid file paths or allowing the user to choose a different file encoding.

The Final Output for the Entire result is

from tkinter import *
from tkinter import filedialog

root = Tk()
root.geometry("300x200")

user_input = input("Enter '1' to type input, '2' to upload a text file: ")

if user_input == '1':
    # Prompt user to type input in the command prompt
    print("Enter the text and type in quit to exit the prompt")
    #user_text = input("Enter text: ")
    while True:
        user_text = input("Enter text: \n")
        #emotion = analyze_emotion(user_text)
        #print(emotion)
        print(user_text)
        if user_text.lower()=="quit":
            print("You have exited the prompt")
            break
elif user_input == '2':
    # Prompt user to upload a text file
    ele= int(input("Enter the no.of elements"))

    # Function to process each line of data
    def process_line(line, n):
        # Delete the first n elements from the line
        modified_line = line.split()[n:]
        # Convert the modified line back to a string and return it
        return ' '.join(modified_line)

    def delete_n_elements(n):
        filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt"), ("All Files", "*.*")))
        with open(filename, "r", encoding='utf-8') as f:
            modified_lines = [process_line(line.strip(), n) for line in f]
        return modified_lines

    # Example usage:
    modified_data = delete_n_elements(ele)
    for line in modified_data:
        print(line)

    #file_path = input("Enter file path: ")
    #with open(file_path, 'r') as file:
    #    user_text = file.read()
else:
    print("Invalid input. Please enter '1' or '2'.")

# Do something with the user_text variable
saidhanush4422 commented 1 year ago

Final Output

from tkinter import *
from tkinter import filedialog

root = Tk()
root.geometry("300x200")

user_input = input("Enter '1' to type input, '2' to upload a text file: ")

if user_input == '1':
    # Prompt user to type input in the command prompt
    print("Enter the text and type in quit to exit the prompt")
    #user_text = input("Enter text: ")
    while True:
        user_text = input("Enter text: \n")
        #emotion = analyze_emotion(user_text)
        #print(emotion)
        print(user_text)
        if user_text.lower()=="quit":
            print("You have exited the prompt")
            break
elif user_input == '2':
    # Prompt user to upload a text file
    ele= int(input("Enter the no.of elements"))

    # Function to process each line of data
    def process_line(line, n):
        # Delete the first n elements from the line
        modified_line = line.split()[n:]
        # Convert the modified line back to a string and return it
        return ' '.join(modified_line)

    def delete_n_elements(n):
        filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Text files", "*.txt"), ("All Files", "*.*")))
        with open(filename, "r", encoding='utf-8') as f:
            modified_lines = [process_line(line.strip(), n) for line in f]
        return modified_lines

    # Example usage:
    modified_data = delete_n_elements(ele)
    for line in modified_data:
        print(line)

    #file_path = input("Enter file path: ")
    #with open(file_path, 'r') as file:
    #    user_text = file.read()
else:
    print("Invalid input. Please enter '1' or '2'.")

# Do something with the user_text variable
Anudeep-23 commented 1 year ago

Ok