1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
"""
Ce script lit un fichier et affiche les lignes qui y apparaissent plusieurs
fois, en indiquant combien de fois elles apparaissent.
Ce code a été testé avec Python 3.6.4.
L'analyse statique du code a été validée par mypy 0.570.
"""
#####################
# Imports and types #
#####################
import os
from typing import Iterable, Mapping, MutableMapping, TypeVar
T = TypeVar('T')
#########
# Paths #
#########
filePath : str = 'test.txt'
#############
# Main code #
#############
def _mainImpl() -> None:
with open(filePath) as file:
mapFromLineToNumberOfOccurrences : Mapping[str, int] = countOccurrencesOfEachElement(file)
printMapFromLineToNumberOfOccurrences(mapFromLineToNumberOfOccurrences)
def countOccurrencesOfEachElement(iterable : Iterable[T]) -> MutableMapping[T, int]:
result : MutableMapping[T, int] = {}
for element in iterable:
if element not in result:
result[element] = 1
else:
result[element] += 1
return result
def printMapFromLineToNumberOfOccurrences(mapFromLineToNumberOfOccurrences : Mapping[str, int]) -> None:
for line in mapFromLineToNumberOfOccurrences:
count : int = mapFromLineToNumberOfOccurrences[line]
if count > 1:
print(line[0:-1] + ' : ' + str(count) + ' occurrences')
if __name__ == '__main__':
try:
_mainImpl()
except Exception as e:
print('Error: ' + str(e))
os.system('pause') |
Partager