Я изменил свой ответ, чтобы лучше отражать ваши пожелания:
from nltk import word_tokenize
with open('file_path') as f:
content = f.read()
# we will use your text example instead:
content = "A professional is a person who is engaged in a certain activity, or occupation, for gain or compensation as means of livelihood; such as a permanent career, not as an amateur or pastime. Due to the personal and confidential nature of many professional services, and thus the necessity to place a great deal of trust in them, most professionals are subject to strict codes of conduct enshrining rigorous ethical and moral obligations."
def Count_Word(word, data):
c = 0
tokens = word_tokenize(data)
for token in tokens:
token = token.lower()
# this plural check is dangerous, if trying to find a word that ends with an 's'
token = token[:-1] if token[-1] == 's' else token
if token == word:
c += 1
return c
print Count_Word('professional', content)
>>>
3
Вот модифицированная версия метода:
def Count_Word(word, data, leading=[], trailing=["'s", "s"]):
c = 0
tokens = word_tokenize(data)
for token in tokens:
token = token.lower()
for lead in leading:
if token.startswith(lead):
token = token.partition(lead)[2]
for trail in trailing:
if token.endswith(trail):
token = token.rpartition(trail)[0]
if token == word:
c += 1
return c
Я добавил к необязательным аргументам, которые представляют собой списки ведущих или конечных частей слова, которые вы хотите обрезать, чтобы найти его ... На e моментом я ставлю только по умолчанию 's
или s
. Но если вы обнаружите, что другие подойдут вам, вы всегда сможете их добавить. Если списки начнут длиться, вы можете сделать их константами.
Что вы пробовали? Взгляните на http://www.daniweb.com/software-development/python/code/216495/wordcount-of-a-text-file-python - может быть полезно – Smajl
Вы хотите посчитать «профессионалы» как экземпляр? Что относительно 'Professional', или' professional, '? Или 'prof-' в конце строки с 'essional' на следующем? Пока вы не определите проблему, вы не сможете ее решить. – abarnert
Кроме того, почему вы открываете файл в режиме 'r + b'? Если вы не хотите писать на него, не добавляйте '+'. Если вы не хотите вручную обрабатывать разные типы строк, наборов символов и т. Д., Не добавляйте 'b'. – abarnert