FILE_NAME = 'file.txt'
wordCounter = {}
with open(FILE_NAME,'r') as fh:
for line in fh:
# Replacing punctuation characters. Making the string to lower.
# The split will spit the line into a list.
word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
for word in word_list:
# Adding the word into the wordCounter dictionary.
if word not in wordCounter:
wordCounter[word] = 1
else:
# if the word is already in the dictionary update its count.
wordCounter[word] = wordCounter[word] + 1
print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)
# printing the words and its occurrence.
for (word,occurance) in wordCounter.items():
print('{:15}{:3}'.format(word,occurance))
Ваш подход верен, но в коде есть некоторые проблемы проектирования: поля
lazy
используются в разделе init
. Поле становится не ленивым emailValid
поле может быть выставлено как LiveData
проверка может быть заключена во внутренний класс, но это не требуется
class RegistrationViewModel : ViewModel() {
val email = MutableLiveData<String>()
val emailConf = MutableLiveData<String>()
@Suppress("UNCHECKED_CAST")
val emailValid: LiveData<Boolean> = MediatorLiveData<Boolean>().apply {
val validator = Validator(::postValue)
addSource(email, validator as Observer<String>)
addSource(emailConf, validator as Observer<String>)
}
private inner class Validator(private val validationConsumer: (Boolean) -> Unit) : Observer<Any> {
override fun onChanged(ignored: Any?) {
//Obviously there is more validation needed but this is just an example
val email = email.value
val emailConf = emailConf.value
validationConsumer(when {
email.isNullOrEmpty() -> false
emailConf.isNullOrEmpty() -> false
email == emailConf -> true
else -> false
})
}
}
}
[1110 ] Если вам требуется некоторая тяжелая проверка, вы можете создать скрытое изменяемое поле для emailValid
и вручную обновить его после завершения проверки фона