Rewriting python code

Hello guys
my friend asked me if he can get my code and i wanna give it to him but im sure he won’t be able to rewrite it. Is it possible if somebody could rewrite my following code:

from math import log

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

vectorizer = TfidfVectorizer()

posting_list = imdb_all.iloc[intersection].sort_values('rating', ascending=False)


def create_query_term_count(posting_list, query_terms):
    posting_list['term_count'] = posting_list['plotterms'].apply(lambda x: len(x.split()))

    # count how many times any of the query terms appear in the plot
    posting_list['query_term_count'] = posting_list['plotterms'].apply(lambda x: len([item for item in x.split() if item in query_terms.split()]))


    # order by the query_term_count column and filter if query_term_count is greater than 0
    return posting_list[posting_list['query_term_count'] > 0].sort_values('query_term_count', ascending=False)



def inverse_document_frequency(all_documents, terms):
    num_documents_with_this_term = 0
    for term in terms.split():
        for index, doc in all_documents.iterrows():
            if term in doc['plotterms'].split():
                num_documents_with_this_term += 1
                if num_documents_with_this_term > 0:
                    return 1.0 + log(float(len(all_documents)) / num_documents_with_this_term)
                else:
                    return 1.0


def cos_sim(df, query):
    X = vectorizer.fit_transform(imdb_all['plotterms'])
    query_vec = vectorizer.transform([query])

    results = cosine_similarity(X,query_vec)
    results = results.flatten()
    imdb_all['cos_sim'] = results


def tf_idf(posting_list, query):
# calculate the term frequency
    tf = posting_list['query_term_count'] / posting_list['term_count']
    posting_list['term_frequency'] = tf
# calculate the inverse document frequency
    idf = inverse_document_frequency(imdb_all, query)
# calculate the TF-IDF score
    posting_list['tf_idf'] = tf * idf


def search(query):
    query_list = create_query_term_count(posting_list, query)
    tf_idf(query_list, query)
    cos_sim(query_list, query)

    return query_list


queries = ['american dream', 'american', 'dream']
for query in queries:
    query_list = search(query)
display(query_list)

best regards
willien

Rewrite your code to do what?

I already rewrote it so its okay

Hay I kinda have the same problem but the code is very short so if you could please just help me rewrite the code if you could I would appreciate it so much.

signL = input("Would you like to sign in or sign up? ").lower()

if signL == "sign up":
    with open("Email.txt", "a") as f:
        email = input("Enter your email: ")
        while "@" not in email or "gmail.com" not in email:
            print("Invalid email, please try again.")
            email = input("Enter your email: ")
        f.write(email + "\n")

        password = input("Enter your new password: ")
        while len(password) < 8 or password.islower() or password.isupper():
            print("Invalid password, please try again.")
            password = input("Enter your new password: ")

        confirm_password = input("Re-enter your password for confirmation: ")
        while confirm_password != password:
            print("Passwords don't match, please try again.")
            confirm_password = input("Re-enter your password for confirmation: ")
       
        with open("Password.txt", "a") as fp:
            fp.write(password + "\n")

    print("Sign up successful!")
       
elif signL == "sign in":
    with open("Email.txt", "r") as f:
        email_list = f.readlines()
        email_index = -1
        while email_index == -1:
            email = input("Enter your email: ")
            for i, line in enumerate(email_list):
                if email in line:
                    email_index = i
                    break
            if email_index == -1:
                print("Email not found, please try again.")
       
        with open("Password.txt", "r") as fp:
            password_list = fp.readlines()
            password = input("Enter your password: ")
            while password_list[email_index].strip() != password:
                password = input("Incorrect password, please try again: ")
           
        print("Sign in successful!")
        # set Login=True or perform other actions as needed

else:
    print("Invalid input, please try again.")

As Steven asked the OP: Rewrite your code to do what?

What do you want said ‘rewrite’ to achieve?

On a more constructive note: your app needs a restart if the user fails to provide an expected response, so maybe:

def options():
    response = ("sign in", "sign up")
    signL = input("Would you like to sign in or sign up? ").lower()
    if signL in response:
        return signL
    else:
        print("Invalid input, please try again.")
        print()
        return False


signL = False
while not signL:
    signL = options()

...

You could define functions (as I have, above) for the rest of your script, such as…

def sign_up():
def sign_in():
def enter_password():

… and do some error checking, such as: what if the file Email.txt does not exist?

Often times, apps can be broken down into a series of functions, with the main body of the code being a driver for the functions.


To add: maybe this is a little more advanced, but is none the less valid…

In ‘real world’ applications, passwords are never (or should never) be stored in clear form.

This is a POC that demonstrates how to check a clear password (AKA a passphrase) against its SHA256 hash; the hash being what is stored in the passwords.txt file (or some-such), but is hard-coded here for convenience:

from hashlib import sha256


def passcheck():
    passphrase = input('Please enter your passphrase: ')
    hashed_passphrase = sha256(passphrase.encode('utf-8')).hexdigest()
    if hashed_passphrase == 'e569b5938d53ccceddf9afe2aa1761a5501065fef73d413430869905fda79875':
        return True
    else:
        print('\nInvalid passphrase\n')


valid = False
while not valid:
    valid = passcheck()

print("Well done; you're in!!")