31.1k views
4 votes
This program reads a file called 'test.txt'. You are required to write two functions that build a wordlist out of all of the words found in the file and print all of the unique words found in the file. Remove punctuations using 'string.punctuation' and 'strip()' before adding words to the wordlist.

Write a function build_wordlist() that takes a 'file pointer' as an argument and reads the contents, builds the wordlist after removing punctuations, and then returns the wordlist. Another function find_unique() will take this wordlist as a parameter and return another wordlist comprising of all unique words found in the wordlist.
Example:
Contents of 'test.txt':
test file
another line in the test file
Output:
['another', 'file', 'in', 'line', 'test', 'the']
This the skeleton for 1:
#build_wordlist() function goes here
#find_unique() function goes here
def main():
infile = open("test.txt", 'r')
word_list = build_wordlist(infile)
new_wordlist = find_unique(word_list)
new_wordlist.sort()
print(new_wordlist)
main()

User Saff
by
5.4k points

1 Answer

7 votes

Answer:

Step-by-step explanation:

The following code has the two requested functions, fully working and tested for bugs. It is written in Python as is the sample code in the question and a sample output can be seen in the picture attached below.

import string

def build_wordlist(file_pointer):

words = file_pointer.read()

words = [word.strip(string.punctuation) for word in words.split()]

return words

def find_unique(word_list):

unique_words = []

for word in word_list:

if word not in unique_words:

unique_words.append(word)

return unique_words

def main():

infile = open("test.txt", 'r')

word_list = build_wordlist(infile)

new_wordlist = find_unique(word_list)

new_wordlist.sort()

print(new_wordlist)

main()

This program reads a file called 'test.txt'. You are required to write two functions-example-1
User NullUserException
by
5.0k points