The canonical code that is closer to your code than the version from
Andrey :
with open('test.txt', 'r') as f:
print(sum(len(line.split()) for line in f.readlines()))
And it is just like you:
with open('test.txt', 'r') as f:
print(sum(map(len, map(str.split, f.readlines()))))
The second task:
# печатаем уникальные слова(ваш вариант с ошибкой)
with open('test.txt', 'r') as f:
for word in set(word.strip() for word in f.read().split()):
print(word)
# выводим слова и их количество(то, что вы подразумавали)
from collections import defaultdict # словарь, для которого можно указать значения по умолчанию
with open('test.txt', 'r') as f:
words = defaultdict(int) # функция, вызывающаяся для каждого нового ключа, int() возвращает 0
for word in (word.strip() for word in f.read().split()):
words[word] += 1 # можно не проверять на наличие ключа, а сразу инкрементировать, т.к. значение по умолчанию - 0
for word, num in words.items():
print(word, '\t', num)