Advertisement
plarmi

pythonwork_14_5

Jul 9th, 2023
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. def count_word_occurrences(file_path, target_word):
  2.     with open(file_path, 'r') as file:
  3.         text = file.read()
  4.        
  5.     # Удаляем знаки пунктуации из текста (за исключением букв и цифр)
  6.     punctuation_marks = '''!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~'''
  7.     text = text.translate(str.maketrans('', '', punctuation_marks))
  8.    
  9.     words = text.split()
  10.     word_count = sum(1 for word in words if word.lower() == target_word.lower())
  11.    
  12.     return word_count
  13.  
  14. # Пример использования
  15. file_path = 'file.txt'       # Путь к текстовому файлу
  16. target_word = 'example'     # Заданное пользователем слово
  17.  
  18. occurrences = count_word_occurrences(file_path, target_word)
  19. print(f"Слово '{target_word}' встречается {occurrences} раз(а) в файле.")
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement