plag.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #pip install -U scikit-learn
  2. #Make sure all the .txt files that need to be checked are in the same directory as the script
  3. import os
  4. from sklearn.feature_extraction.text import TfidfVectorizer
  5. from sklearn.metrics.pairwise import cosine_similarity
  6. user_files = [doc for doc in os.listdir() if doc.endswith('.txt')]
  7. user_notes = [open(_file, encoding='utf-8').read()
  8. for _file in user_files]
  9. def vectorize(Text): return TfidfVectorizer().fit_transform(Text).toarray()
  10. def similarity(doc1, doc2): return cosine_similarity([doc1, doc2])
  11. vectors = vectorize(user_notes)
  12. s_vectors = list(zip(user_files, vectors))
  13. plagiarism_results = set()
  14. def check_plagiarism():
  15. global s_vectors
  16. for student_a, text_vector_a in s_vectors:
  17. new_vectors = s_vectors.copy()
  18. current_index = new_vectors.index((student_a, text_vector_a))
  19. del new_vectors[current_index]
  20. for student_b, text_vector_b in new_vectors:
  21. sim_score = similarity(text_vector_a, text_vector_b)[0][1]
  22. student_pair = sorted((student_a, student_b))
  23. score = (student_pair[0], student_pair[1], sim_score)
  24. plagiarism_results.add(score)
  25. return plagiarism_results
  26. for data in check_plagiarism():
  27. print(data)