File Analysis
Write a program that reads the contents of two text files and compares them in the following ways:
Hint: Use set operations to perform these analyses.
File Analysis Program code:
def compareBothFiles(firstFilePath, secondFilePath):
# Read the contents of the first file
with open(firstFilePath, 'r') as file1:
contents1 = file1.read()
# Read the contents of the second file
with open(secondFilePath, 'r') as file2:
contents2 = file2.read()
# Split the contents of each file into individual words
words1 = set(contents1.split())
words2 = set(contents2.split())
# Display a list of all unique words contained in both files
uniqueWords = words1.union(words2)
print("Unique Words in Both Files:")
print(uniqueWords)
# Display a list of words that appear in both files
common_words = words1.intersection(words2)
print("\nCommon Words in Both Files:")
print(common_words)
# Display a list of words that appear in the first file but not the second
uniqueWords_file1 = words1.difference(words2)
print("\nWords in File 1 but Not in File 2:")
print(uniqueWords_file1)
# Display a list of words that appear in the second file but not the first
uniqueWords_file2 = words2.difference(words1)
print("\nWords in File 2 but Not in File 1:")
print(uniqueWords_file2)
# Display a list of words that appear in either the first or second file but not both
exclusive_words = words1.symmetric_difference(words2)
print("\nWords Exclusive to Either File:")
print(exclusive_words)
# Usage example
firstFilePath = "firstFileData.txt" # Replace with the path to your first text file
secondFilePath = "secondFileData.txt" # Replace with the path to your second text file
compareBothFiles(firstFilePath, secondFilePath)
Input Data:
"firstFileData.txt" data:
John
Charless
Mohamad
Jacob
Elliot
Mason
Miles
Theodore
Nathan
Owen
Alexander
"secondFileData.txt" data:
William
Charless
Oliver
Grayson
Leo
Jack
Nathan
Owen
Executed Output:
Unique Words in Both Files:
{'Elliot', 'Owen', 'Grayson', 'Mason', 'Nathan', 'Charless', 'Jacob', 'Miles', 'John', 'William', 'Alexander', 'Jack', 'Theodore', 'Leo', 'Mohamad', 'Oliver'}
Common Words in Both Files:
{'Owen', 'Charless', 'Nathan'}
Words in File 1 but Not in File 2:
{'Elliot', 'Alexander', 'Mason', 'Theodore', 'Jacob', 'Mohamad', 'Miles', 'John'}
Words in File 2 but Not in File 1:
{'William', 'Grayson', 'Jack', 'Leo', 'Oliver'}
Words Exclusive to Either File:
{'William', 'Grayson', 'Jack', 'Alexander', 'Elliot', 'Mason', 'Theodore', 'Miles', 'Leo', 'Jacob', 'Mohamad', 'Oliver', 'John'}