We need to implement a Python function to detect plagiarism in text documents. This is a broad task. Likely the user expects a function that can compare two text documents and return some similarity score or plagiarism detection result. Possibly also handle multiple documents? But the prompt says "detect plagiarism in text documents." Could be a single function that takes two strings (document contents) and returns a similarity percentage or a boolean if above threshold.
We need to decide on the approach. Common methods: using n-gram overlap (shingling), Jaccard similarity, cosine similarity with TF-IDF, or using more advanced techniques like using word embeddings. For simplicity and typical interview context, they might expect using n-gram shingling and Jaccard similarity, or using Python's difflib.
But the user says "Implement a Python function to detect plagiarism in text documents." Could be they want a solution that uses a known algorithm like "winnowing" or "fingerprinting". However, we must provide a practical solution.
Given it's a code generation, we can produce a function that takes two texts, preprocesses them (lowercase, remove punctuation, maybe tokenize), then compute similarity using cosine similarity of TF-IDF vectors from scikit-learn? But that would require external libraries. The instruction might not allow external libraries beyond standard library. We should use only Python standard library unless specified otherwise.
Better to use built-in modules: difflib.SequenceMatcher for quick similarity ratio. That is a simple plagiarism detection: if similarity > threshold, then likely plagiarized. But that's not sophisticated.
Alternatively, we could implement shingling: split text into k-grams (sets of contiguous words), compute Jaccard similarity between the sets. That's a standard approach.
We need to handle case-insensitivity, punctuation removal. Use regular expressions.
Let's design:
- Preprocess: convert to lowercase, remove non-alphanumeric characters (maybe keep spaces). Use re.sub(r'[^a-z0-9\s]', '', text.lower()). Then split into words.
- Generate shingles (k-grams) of words: e.g., for k=3, create tuples of 3 consecutive words.
- Compute Jaccard similarity: intersection/union of shingle sets.
- Return similarity score (0-1). Optionally threshold.
Edge cases: empty text, very short text.
We could also implement a rolling hash for efficiency for large documents, but for simplicity set approach is fine.
Alternatively, we could use difflib's SequenceMatcher on the word sequences, which gives a ratio. That is simpler. Let's consider: SequenceMatcher from difflib compares sequences and returns a similarity measure. It works on lists of words. That could be a good solution.
But many plagiarism detection methods use fingerprinting with winnowing to be robust to small changes. But implementing winnowing is more complex.
Given it's an open-ended prompt, we should provide a function that is plausible and explain the approach.
The user likely wants a function that can detect plagiarism between two texts, possibly also among a set of documents? The phrase "detect plagiarism in text documents" could be interpreted as: given a corpus of documents, find pairs that are suspiciously similar. But the instruction says "Implement a Python function" singular, so probably a function that compares two documents.
We'll implement a function detect_plagiarism(text1, text2, threshold=0.8) that returns True if similarity > threshold.
We need to decide on method: Jaccard similarity on word n-grams with n=3 is a good choice.
Let's implement:
import re
from typing import Set, Tuple
def get_shingles(text: str, k: int = 3) -> Set[Tuple[str, ...]]:
# Preprocess: lowercase, remove punctuation, split into words
words = re.findall(r'\w+', text.lower())
# If fewer than k words, return empty set or handle?
if len(words) < k:
# return set of a single tuple of all words? Actually for Jaccard, empty sets yield similarity 1 if both empty else 0? Better to handle edge.
return set()
shingles = set()
for i in range(len(words) - k + 1):
shingles.add(tuple(words[i:i+k]))
return shingles
def jaccard_similarity(set1: set, set2: set) -> float:
if not set1 and not set2:
return 1.0
intersection = len(set1 & set2)
union = len(set1 | set2)
return intersection / union
def detect_plagiarism(text1: str, text2: str, threshold: float = 0.8, k: int = 3) -> bool:
shingles1 = get_shingles(text1, k)
shingles2 = get_shingles(text2, k)
similarity = jaccard_similarity(shingles1, shingles2)
return similarity >= threshold
But we might also want to return similarity score.
Now, maybe they want a more advanced function that can handle many documents? Could create a class PlagiarismDetector that indexes shingles for each document and then can query. But the instruction is to "implement a Python function", not a class.
We could also mention that we are using n-gram shingling and Jaccard similarity.
Given the simplicity, we might also consider using difflib:
import difflib
def detect_plagiarism(text1, text2, threshold=0.8):
seq = difflib.SequenceMatcher(None, text1.lower(), text2.lower())
return seq.ratio() >= threshold
But this compares characters, not words, so it might be too sensitive to small changes. However, it's simple.
Better to use word-level SequenceMatcher:
def detect_plagiarism(text1, text2, threshold=0.8):
words1 = re.findall(r'\w+', text1.lower())
words2 = re.findall(r'\w+', text2.lower())
seq = difflib.SequenceMatcher(None, words1, words2)
return seq.ratio() >= threshold
That gives a decent similarity measure.
We'll choose the shingling approach as it's a standard plagiarism detection technique (like used in MOSS). Actually MOSS uses winnowing but similar.
We'll implement with shingles.
But we must consider performance: sets of tuples might be memory heavy for large texts but fine for moderate.
We'll also handle empty texts.
We'll produce final answer with code and explanation.
But the user only said "Implement a Python function to detect plagiarism in text documents." That's it. So we need to output the function.
Probably they expect a solution that can be used in an interview setting. Let's provide a clean, well-commented function.
I'll write:
import re
from typing import List, Set, Tuple
def preprocess(text: str) -> List[str]:
"""Convert text to lowercase and split into words, removing non-alphanumeric characters."""
return re.findall(r'\b\w+\b', text.lower())
def get_shingles(words: List[str], k: int = 3) -> Set[Tuple[str, ...]]:
"""Generate k-shingles (k consecutive words) from a list of words."""
shingles = set()
for i in range(len(words) - k + 1):
shingles.add(tuple(words[i:i+k]))
return shingles
def jaccard_similarity(set_a: Set, set_b: Set) -> float:
"""Compute Jaccard similarity between two sets."""
if not set_a and not set_b:
return 1.0 # Both empty are considered identical
intersection = len(set_a & set_b)
union = len(set_a | set_b)
return intersection / union
def detect_plagiarism(doc1: str, doc2: str, threshold: float = 0.8, shingle_size: int = 3) -> float:
"""
Detect plagiarism between two text documents.
Returns the Jaccard similarity score (0 to 1) and a boolean indicating if similarity >= threshold.
"""
words1 = preprocess(doc1)
words2 = preprocess(doc2)
shingles1 = get_shingles(words1, shingle_size)
shingles2 = get_shingles(words2, shingle_size)
similarity = jaccard_similarity(shingles1, shingles2)
return similarity # Could also return similarity >= threshold
# Example usage:
if __name__ == "__main__":
text1 = "The quick brown fox jumps over the lazy dog."
text2 = "A fast brown fox leaps over a sleepy dog."
sim = detect_plagiarism(text1, text2)
print(f"Similarity: {sim:.2f}")
if sim >= 0.8:
print("Plagiarism likely.")
else:
print("Plagiarism unlikely.")
But the function returns similarity; we might want to return boolean if threshold provided. We can modify.
Given the prompt: "Implement a Python function to detect plagiarism in text documents." Possibly they want a function that returns True/False. I'll adjust.
Define:
def is_plagiarized(doc1: str, doc2: str, threshold: float = 0.8, shingle_size: int = 3) -> bool:
"""Return True if the similarity between doc1 and doc2 is above threshold."""
words1 = preprocess(doc1)
words2 = preprocess(doc2)
shingles1 = get_shingles(words1, shingle_size)
shingles2 = get_shingles(words2, shingle_size)
similarity = jaccard_similarity(shingles1, shingles2)
return similarity >= threshold
But we can also combine.
Better to provide a function that returns the similarity score and optionally threshold check.
I think the simplest is to implement a function plagiarism_score that returns similarity, and then a wrapper.
But to keep it one function, we can have it return a boolean with default threshold.
I'll produce final code with the following signature:
def detect_plagiarism(text1: str, text2: str, threshold: float = 0.8) -> bool:
Implementation using shingles.
But we must be careful: if both texts are very short, shingle set may be empty leading to division by zero or similarity 1. Our jaccard function handles empty both sets as 1. That might cause false positive: two empty texts considered identical. That's okay; they are both empty. But if one empty and other non-empty, union is non-zero, intersection 0 => similarity 0. That's fine.
We can also handle the case when len(words) < shingle_size: then shingles set will be empty (since loop range negative yields no additions). So for short texts, we'll have empty sets. That's okay but might treat any two short texts (less than 3 words) as identical (similarity 1) if both have fewer than 3 words. That's a limitation. We could adjust to use a smaller shingle size or use whole text as shingle. But for simplicity, we can assume documents are long enough.
Alternatively, we can fallback to word-level Jaccard if shingle set empty. But that's extra.
I think it's acceptable.
We'll produce final answer with explanation.
But the instruction: "Implement a Python function to detect plagiarism in text documents." So the answer should be the code. In the chat, we need to output the function. Usually we output the code block.
We'll also include a brief explanation before the code.
Thus final response: explanation and code.
We must follow the guidelines: The assistant should not mention it's an AI, just provide helpful answer. So we'll provide a clear answer.
Let's write:
We can detect plagiarism by comparing the similarity of documents using shingling and Jaccard similarity. The approach:
- Preprocess each document: convert to lowercase and split into words, ignoring punctuation.
- Generate k-shingles: sets of consecutive k words.
- Compute Jaccard similarity between the two shingle sets.
- If similarity exceeds a threshold (e.g., 0.8), flag as potential plagiarism.
Here's the Python implementation:
import re
from typing import List, Set, Tuple
def _preprocess(text: str) -> List[str]:
"""Return list of words in lowercase, stripping non-alphanumeric characters."""
return re.findall(r'\b\w+\b', text.lower())
def _shingles(words: List[str], k: int = 3) -> Set[Tuple[str, ...]]:
"""Generate set of k-shingles (tuples of k consecutive words)."""
if len(words) < k:
# If text is too short, fall back to using the whole word list as a single shingle.
# Alternatively, return an empty set; adjust as needed.
return {tuple(words)} if words else set()
return {tuple(words[i:i+k]) for i in range(len(words) - k + 1)}
def _jaccard(set_a: Set, set_b: Set) -> float:
"""Jaccard similarity between two sets."""
if not set_a and not set_b:
return 1.0
inter = len(set_a & set_b)
union = len(set_a | set_b)
return inter / union
def detect_plagiarism(text1: str, text2: str, threshold: float = 0.8, shingle_size: int = 3) -> bool:
"""
Determine whether two texts are likely plagiarized based on shingle Jaccard similarity.
Returns True if similarity >= threshold.
"""
words1 = _preprocess(text1)
words2 = _preprocess(text2)
shingles1 = _shingles(words1, shingle_size)
shingles2 = _shingles(words2, shingle_size)
similarity = _jaccard(shingles1, shingles2)
return similarity >= threshold
# Example usage
if __name__ == "__main__":
doc1 = "The quick brown fox jumps over the lazy dog."
doc2 = "A fast brown fox leaps over a sleepy dog."
if detect_plagiarism(doc1, doc2):
print("Potential plagiarism detected.")
else:
print("No plagiarism detected.")
This should work for moderate-length documents. For large collections or more robust detection, consider using winnowing or fuzzy hashing.
We'll output that.
import re
from typing import List, Set, Tuple
def _preprocess(text: str) -> List[str]:
"""Return a list of words in lowercase, ignoring punctuation."""
return re.findall(r'\b\w+\b', text.lower())
def _shingles(words: List[str], k: int = 3) -> Set[Tuple[str, ...]]:
"""
Generate a set of k‑shingles (tuples of k consecutive words).
If the word list is shorter than k, the whole list is treated as one shingle.
"""
if len(words) < k:
return {tuple(words)} if words else set()
return {tuple(words[i:i + k]) for i in range(len(words) - k + 1)}
def _jaccard(set_a: Set, set_b: Set) -> float:
"""Compute Jaccard similarity between two sets."""
if not set_a and not set_b:
return 1.0
inter = len(set_a & set_b)
union = len(set_a | set_b)
return inter / union
def detect_plagiarism(text1: str, text2: str,
threshold: float = 0.8,
shingle_size: int = 3) -> bool:
"""
Determine whether two text documents are likely plagiarized.
The function uses k‑shingle (k‑gram) sets and Jaccard similarity.
Returns True if the similarity is at or above the given threshold.
Args:
text1: First document text.
text2: Second document text.
threshold: Similarity threshold (default 0.8).
shingle_size: Number of consecutive words per shingle (default 3).
Returns:
bool: True if potential plagiarism is detected.
"""
words1 = _preprocess(text1)
words2 = _preprocess(text2)
shingles1 = _shingles(words1, shingle_size)
shingles2 = _shingles(words2, shingle_size)
similarity = _jaccard(shingles1, shingles2)
return similarity >= threshold
# Example usage
if __name__ == "__main__":
doc1 = "The quick brown fox jumps over the lazy dog."
doc2 = "A fast brown fox leaps over a sleepy dog."
if detect_plagiarism(doc1, doc2):
print("Potential plagiarism detected.")
else:
print("No plagiarism detected.")