python problem: This program reads a file called \'test.txt\'. You are required
ID: 3606994 • Letter: P
Question
python problem:
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']
use the code below:
#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()
The output should be like:
['a', 'another', 'file', 'guess', 'here', 'in', 'is', 'it', 'line', 'more', 'not', 'now', 'one', 'stopping', 'test', 'that', 'the', 'this', 'was']
Explanation / Answer
import string def build_wordlist(f): text=f.read() l=text.split(' ') words=[] for i in l: i=i.split(' ') for k in i: words.append(k.strip(string.punctuation)) return words def find_unique(l): a=[] for i in l: if i not in a: a.append(i) return a 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()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.