Как посчитать количество слов в списке, если их больше одного?

#python #python-3.x

Вопрос:

Например, у меня есть текст,

 text = '''
Wales’ greatest moment. Lille is so close to the Belgian border, this was 
essentially a home game for one of the tournament favourites. Their confident supporters mingled 
with their new Welsh fans on the streets, buying into the carnival spirit - perhaps 
more relaxed than some might have been before a quarter-final because they 
thought this was their time.
In the driving rain, Wales produced the best performance in their history to carry 
the nation into uncharted territory. Nobody could quite believe it.
'''
 

Мне нужно получить количество слов в этом тексте, мы вводим слова с помощью input().
Введите будет список, диктуйте, установите это необходимое условие.
Также не ясно, как убрать внимание к знакам препинания.
Мое решение, но, возможно, есть более чистый способ.

 text = list(text.split(' '))
word = input('Enter a word: ')
for i in text:
    if text.count(word) < 2:
        break
    if word in text:
        print(f'{word} - {text.count(word)}')
        break
 

Выход:

это — 2

в — 7

«Момент» встречается в тексте только один раз, мы не выводим его

Комментарии:

1. Не уверен, зачем вам здесь нужен цикл for.

Ответ №1:

Вы можете думать об этом как о двух шагах:

  1. Очистите входные данные
  2. Найди графа

Быстрый способ очистить ввод-сначала удалить все знаки препинания, используя translate в сочетании с string.punctuation :

 import string
clean = text.translate(str.maketrans('', '', string.punctuation)).split()
 

Теперь у вас есть весь текст без знаков препинания и вы можете разделить его на слова и посчитать:

 import string 

clean = text.translate(str.maketrans('', '', string.punctuation)).split()

word = "this"

count = clean.count(word)
if count > 1:
    print(f'{word} - {count}')
# prints: this - 2
 

Так как вы используете count , вам не нужно выполнять цикл. Просто будьте осторожны, чтобы не звонить несколько раз, если в этом нет необходимости. Каждый раз, когда вы это делаете, ему нужно просматривать весь список. Обратите внимание, что выше код вызывает его один раз и сохраняет, чтобы мы могли использовать счетчик в нескольких местах.

Ответ №2:

Вы можете использовать коллекции.Счетчик() для получения словаря количества вхождений каждого элемента в списке:

 import collections

text = '''
Wales’ greatest moment. Lille is so close to the Belgian border, this was 
essentially a home game for one of the tournament favourites. Their confident supporters mingled 
with their new Welsh fans on the streets, buying into the carnival spirit - perhaps 
more relaxed than some might have been before a quarter-final because they 
thought this was their time.
In the driving rain, Wales produced the best performance in their history to carry 
the nation into uncharted territory. Nobody could quite believe it.
'''
word = input('Enter a word: ')

# Remove punctuation from text
for char in text:
    if char.lower() not in "abcdefghijklmnopqrstuvwxyz ":
        text = text.replace(char, "")

wordcount = collections.Counter(text.split())
print(f"{word} - {wordcount[word]}")
 

Комментарии:

1. Вы игнорируете знаки препинания. Так, например, вы получаете счет 0 «за territory «.