get_all_signatures obtains an authorship signature for every book in a directory of known authors. It returns a dictionary whose keys are filenames and whose values are signatures. section 11.3.1 section 11.5.11
The function follows a small, reusable process:
- Read each book and pass its text to make_signature rather than duplicating signature-calculation work. section 11.3.1
Reading the known_authors directory
Calling get_all_signatures('known_authors') produces entries such as Arthur_Conan_Doyle.txt and Jane_Austen.txt, each paired with a five-value signature list. The implementation needs import os and encoding='utf-8'; otherwise it can raise NameError or UnicodeDecodeError.
Listing 11.13 Obtain all signatures from known authors: Try 1
def get_all_signatures(known_dir):
'''
known_dir is the name of a directory of books.
For each file in directory known_dir, determine its signature.
Return a dictionary where each key is
the name of a file, and the value is its signature.
'''
signatures = {} #1
for filename in os.listdir(known_dir): #2
with open(os.path.join(known_dir, #3
filename)) as f: #3
text = f.read() #4
signatures[filename] = make_signature(text) #5
return signatures
Inspect the complete function listing, including directory iteration, file reading, make_signature calls, and dictionary construction. section 11.5.11
