As one would expect, Microsoft Word includes a feature to count the words in a document; it also includes the ability to count the characters. Knowing the character count of a document is important for any business owner. For example, as a freelance writer your client may have specific character counts they want you to obtain; for other business owners, perhaps the contact form for your client is character-count specific. When you need to check the character count in Microsoft Word, you can do so in the same way you check the word count.
-
Open the document in Word that you want to count the characters in.
-
Click the «Review» tab.
-
Click «Word Count» in the Proofing section. The Word Count window opens and displays the numbers of characters in the document with and without spaces.
-
Click «Close» to close the Word Count window.
I am trying to count the number of times ‘e’ appears in a word.
def has_no_e(word): #counts 'e's in a word
letters = len(word)
count = 0
while letters >= 0:
if word[letters-1] == 'e':
count = count + 1
letters = letters - 1
print count
It seems to work fine except when the word ends with an ‘e’. It will count that ‘e’ twice. I have no idea why. Any help?
I know my code may be sloppy, I’m a beginner! I’m just trying to figure out the logic behind what’s happening.
asked Dec 30, 2010 at 14:52
1
>>> word = 'eeeooooohoooooeee'
>>> word.count('e')
6
Why not this?
answered Dec 30, 2010 at 14:58
user225312user225312
125k68 gold badges172 silver badges181 bronze badges
As others mention, you can implement the test with a simple word.count('e')
. Unless you’re doing this as a simple exercise, this is far better than trying to reinvent the wheel.
The problem with your code is that it counts the last character twice because you are testing index -1
at the end, which in Python returns the last character in the string. Fix it by changing while letters >= 0
to while letters > 0
.
There are other ways you can tidy up your code (assuming this is an exercise in learning):
- Python provides a nice way of iterating over a string using a
for
loop. This is far more concise and easier to read than using awhile
loop and maintaining your own counter variable. As you’ve already seen here, adding complexity results in bugs. Keep it simple. - Most languages provide a
+=
operator, which for integers adds the amount to a variable. It’s more concise thancount = count + 1
. - Use a parameter to define which character you’re counting to make it more flexible. Define a default argument for using
char='e'
in the parameter list when you have an obvious default. - Choose a more appropriate name for the function. The name
has_no_e()
makes the reader think the code checks to see if the code has no e, but what it actually does is counts the occurrences of e.
Putting this all together we get:
def count_letter(word, char='e'):
count = 0
for c in word:
if c == char:
count += 1
return count
Some tests:
>>> count_letter('tee')
2
>>> count_letter('tee', 't')
1
>>> count_letter('tee', 'f')
0
>>> count_letter('wh' + 'e'*100)
100
answered Dec 30, 2010 at 14:58
moinudinmoinudin
132k45 gold badges189 silver badges214 bronze badges
Why not simply
def has_no_e(word):
return sum(1 for letter in word if letter=="e")
answered Dec 30, 2010 at 14:54
Tim PietzckerTim Pietzcker
325k58 gold badges500 silver badges555 bronze badges
The problem is that the last value of ‘letters’ in your iteration is ‘0’, and when this happens you look at:
word[letters-1]
meaning, you look at word[-1], which in python means «last letter of the word».
so you’re actually counting correctly, and adding a «bonus» one if the last letter is ‘e’.
answered Dec 30, 2010 at 14:58
YonatanYonatan
1,15715 silver badges33 bronze badges
It will count it twice when ending with an e because you decrement letters
one time too many (because you loop while letters >= 0
and you should be looping while letters > 0
). When letters
reaches zero you check word[letters-1]
== word[-1]
which corresponds to the last character in the word.
answered Dec 30, 2010 at 14:59
Many of these suggested solutions will work fine.
Know that, in Python, list[-1] will return the last element of the list.
So, in your original code, when you were referencing word[letters-1] in a while loop constrained by letters >= 0, you would count the ‘e’ on the end of the word twice (once when letters was the length-1 and a second time when letters was 0).
For example, if my word was «Pete» your code trace would look like this (if you printed out word[letter] each loop.
e (for word[3])
t (for word[2])
e (for word[1])
P (for word[0])
e (for word[-1])
Hope this helps to clear things up and to reveal an interesting little quirk about Python.
answered Dec 30, 2010 at 15:05
@marcog makes some excellent points;
in the meantime, you can do simple debugging by inserting print statements —
def has_no_e(word):
letters = len(word)
count = 0
while letters >= 0:
ch = word[letters-1] # what is it looking at?
if ch == 'e':
count = count + 1
print('{0} <-'.format(ch))
else:
print('{0}'.format(ch))
letters = letters - 1
print count
then
has_no_e('tease')
returns
e <-
s
a
e <-
t
e <-
3
from which you can see that
- you are going through the string in reverse order
- it is correctly recognizing e’s
- you are ‘wrapping around’ to the end of the string — hence the extra e if your string ends in one
answered Dec 30, 2010 at 16:50
Hugh BothwellHugh Bothwell
54.7k8 gold badges84 silver badges99 bronze badges
If what you really want is ‘has_no_e’ then the following may be more appropriate than counting ‘e’s and then later checking for zero,
def has_no_e(word):
return 'e' not in word
>>> has_no_e('Adrian')
True
>>> has_no_e('test')
False
>>> has_no_e('NYSE')
True
If you want to check there are no ‘E’s either,
def has_no_e(word):
return 'e' not in word.lower()
>>> has_no_e('NYSE')
False
answered Dec 31, 2010 at 16:01
You don’t have to use a while-loop. Strings can be used for-loops in Python.
def has_no_e(word):
count = 0
for letter in word:
if letter == "e":
count += 1
print count
or something simpler:
def has_no_e(word):
return sum(1 for letter in word if letter=="e")
answered Dec 30, 2010 at 14:57
NopeNope
34.3k42 gold badges94 silver badges119 bronze badges
- You can get a character count in a Word document by selecting the «Review» tab and clicking «Word Count.»
- You can find both the number of characters with spaces and the character count not including spaces.
- You can add the Word Count dialog box to the Quick Access toolbar so it’s always one click away.
On occasion, you may need to ensure your document has a particular number of words. Microsoft Word makes it easy to keep track of your word count two different ways – via the status bar at the bottom of the screen and in the Review tab of the ribbon. It’s less common to need the character count, but it’s just as easy to find via the ribbon’s Review tab.
Word tracks many statistics for you: the total number of pages, paragraphs, line, words, and characters. Word distinguishes between the total number of characters in your document with or without including spaces. There might be times when you need to know one or the other, but if you have a need to write a certain number of characters and the requirements don’t specify, you can usually assume it’s the total number of characters including spaces.
How to get a character count in Word with one click
You can add Word Count to Word’s Quick Access toolbar — that’s the row of icons at the top left of the title bar. After you add it, you can click the icon to get a word and character count without first going to the Review tab of the ribbon.
- In Word for Windows, click the «Review» tab and right-click «Word Count.» Then, in the menu, click «Add to Quick Access Toolbar.»
Dave Johnson/Insider
- In Word for the Mac, click the down-arrow at the right of the Quick Access Toolbar in the Word title bar. Choose «More Commands…» In the Ribbon & Toolbar dialog box, click the Choose Commands From menu and choose «Review.» Scroll to the bottom and click «Word Count…» then click the right arrow to move it to the Customize Quick Access Toolbar list. Click «Save.»
Dave Johnson/Insider
Dave Johnson
Freelance Writer
Dave Johnson is a technology journalist who writes about consumer tech and how the industry is transforming the speculative world of science fiction into modern-day real life. Dave grew up in New Jersey before entering the Air Force to operate satellites, teach space operations, and do space launch planning. He then spent eight years as a content lead on the Windows team at Microsoft. As a photographer, Dave has photographed wolves in their natural environment; he’s also a scuba instructor and co-host of several podcasts. Dave is the author of more than two dozen books and has contributed to many sites and publications including CNET, Forbes, PC World, How To Geek, and Insider.
Read more
Read less
In Python, we can easily count the letters in a word using the Python len() function and list comprehension to filter out characters which aren’t letters.
def countLetters(word):
return len([x for x in word if x.isalpha()])
print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))
#Output:
4
18
This is equivalent to looping over all letters in a word and checking if each character is a letter.
def countLetters(word):
count = 0
for x in word:
if x.isalpha():
count = count + 1
return count
print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))
#Output:
4
18
If you’d like to get the count of each letter in Python, you can use the Python collections module.
import collections
print(collections.Counter("Word"))
#Output:
Counter({'W': 1, 'o': 1, 'r': 1, 'd': 1})
If you’d like to get the letters of all words in a string, we can use the Python split() function in combination with the len() function.
string_of_words = "This is a string of words."
letter_counts = []
for x in string_of_words.split(" "):
letter_counts.append(len([x for x in word if x.isalpha()]))
print(letter_counts)
#Output:
[4, 2, 1, 6, 2, 5]
When working with strings, it is very useful to be able to easily extract information about our variables.
One such piece of information which is valuable is the number of letters a string has.
We can use the Python len() function to get the number of letters in a string easily.
print(len("Word"))
#Output:
4
If you have a string with punctuation or numbers in it, we can use list comprehension to filter out the characters which aren’t letters and then get the length of this new string.
def countLetters(word):
return len([x for x in word if x.isalpha()])
print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))
#Output:
4
18
If you don’t want to use list comprehension, loop over each element in the string and see if it is a letter or not with the Python isalpha() function.
def countLetters(word):
count = 0
for x in word:
if x.isalpha():
count = count + 1
return count
print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))
#Output:
4
18
Finding Count of All Letters in a Word Using Python
In Python, we can also find the unique count of all letters in a word, and the number of times each letter appears in a word.
The Python collections module is very useful and provides a number of functions which allow us to create new data structures from lists.
One such data structure is the Counter data structure.
The Counter data structure counts up all of the occurrences of a value in a list.
To get the count of all letters in a word, we can use the Python collections Counter data structure in the following Python code.
import collections
print(collections.Counter("Word"))
#Output:
Counter({'W': 1, 'o': 1, 'r': 1, 'd': 1})
If you then want to get the count of any particular letter, you can access the count just like you would access a value in a dictionary.
import collections
c = collections.Counter("Word")
print(c["W"])
#Output:
1
Counting Letters of All Words in a String Using Python
When processing strings in a program, it can be useful to know how many words there are in the string, and how many letters are in each word. Using Python, we can easily get the number of letters in each word in a string with the Python len() function.
Let’s say you have a string which is a sentence (in other words, each word in the sentence is delimited by a space).
We can use the Python split() function to change the string into a list, and then loop over the list to get the length of each word in a string.
Below is a Python function which will count the letters in all words in a string using Python.
string_of_words = "This is a string of words."
letter_counts = []
for x in string_of_words.split(" "):
letter_counts.append(len([x for x in word if x.isalpha()]))
print(letter_counts)
#Output:
[4, 2, 1, 6, 2, 5]
Hopefully this article has been useful for you to learn how to count letters in words in Python.
Лично я считаю, что исходный код Python легче читать, когда все делается с отступом в четыре пробела. Итак, вот ваша функция снова с более широким отступом:
def count_letter(mylist):
count = 0
for i in range(len(mylist)):
if letter in i:
count += 1
a_list.append(i)
return a_list
print(len(a_list))
for i in range(...)
будет перебирать набор целых чисел. Итак, будет принимать новое целочисленное значение для каждой итерации цикла. Сначала будет
0
, тогда
1
на следующей итерации и т. д.
Затем вы спрашиваете
if letter in i:
. Это никогда не может быть правдой. представляет собой строку и является целым числом. Строка никогда не может быть целым числом, поэтому этот оператор if никогда не будет выполнен. Скорее, вы хотите проверить, есть ли
letter
находится в текущем слове (ое слово в списке). Оператор if должен гласить:
if letter in mylist[i]:
...
Где текущее слово.
Затем вы увеличиваете и добавляете
i
к . Вы, вероятно, хотели добавить
mylist[i]
к, но я не понимаю, зачем тебе вообще нужно
a_list
. Вам просто нужно, так как это отслеживает, сколько слов вы встретили на данный момент, для которых выполняется условие.
count
также является переменной, которую вы должны возвращать в конце, поскольку это цель функции: вернуть количество слов (а не самих слов), содержащих определенную букву.
Кроме того, как ваш финал
print
Оператор с отступом делает его частью тела функции. Однако это после символа, что означает, что у него никогда не будет возможности напечатать. Когда вы используете
return
внутри функции он завершает функцию, и поток выполнения возвращается в то место, из которого функция была первоначально вызвана.
Последнее изменение, которое необходимо применить, заключается в том, что ваша функция должна принимать букву для поиска в качестве параметра. Сейчас ваша функция принимает только один параметр — список слов для поиска.
Вот изменения, которые я бы применил к вашему коду:
def count_letter(words, letter): # I find 'words' is a better name than 'mylist'.
count = 0
for i in range(len(words)):
current_word = words[i]
if letter in current_word:
count += 1
return count
Вот как вы можете использовать эту функцию:
words = ["hello", "world", "apple", "sauce"]
letter = "e"
count = count_letter(words, letter)
print("The letter '{}' appeared in {} words.".format(letter, count))
Выход:
The letter 'e' appeared in 3 words.
Задача состояла в том, чтобы написать функцию с именем count_letter
, которая берет список слов и определенную букву и возвращает количество слов, в которых эта буква встречается хотя бы один раз. И мы должны использовать цикл for
. Итак, я составил список некоторых языков программирования и букву «а» и попытался применить все, что мы узнали до сих пор, а также несколько руководств в Интернете, чтобы понять, как перевести человеческую логику в строки кода, но, очевидно, я что-то упускаю, потому что это не так. не работает Вот как мой код выглядит на данный момент:
mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
a_list = []
def count_letter(mylist):
count = 0
for i in range(len(mylist)):
if letter in i:
count += 1
a_list.append(i)
return a_list
print(len(a_list))
Результат — нет результата. Компилятор онлайн-python возвращает ответ ** Процесс завершен — код возврата: 0 ** Мой вопрос: что я мог пропустить или неправильно расположить, что цикл не работает. Я хочу понять это для себя. В учебниках я нашел одну конструкцию, которая возвращает правильный ответ (и выглядит очень элегантно и компактно), но у нее нет никакой функции, поэтому это не совсем то, что нам нужно было написать:
mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
res = len ([ele for ele in mylist if letter in ele])
print ('Amount of words containing a: ' +str(res))
Здесь ответ системы: 3
, как и ожидалось.
Скажите, пожалуйста, что я должен проверить в коде № 1.
4 ответа
Несколько ошибок, которые я нашел в вашем коде:
-
Когда вы выполняете for i in range(len(mylist)), вы фактически перебираете числа 1,2,… вместо элементов mylist. Таким образом, вы должны использовать «for i in mylist» для перебора элементов массива mylist.
-
Когда вы возвращаетесь из функции, код после возврата не выполняется. Поэтому вы должны сначала напечатать его, а затем вернуться из функции.
-
Не забудьте вызвать функцию. В противном случае функция не будет выполнена.
-
Нет необходимости использовать переменную count, так как вы можете получить доступ к длине, используя метод len.
mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
a_list = []
def count_letter(mylist):
for i in mylist:
if letter in i:
a_list.append(i)
print(len(a_list))
return a_list
print(count_letter(mylist))
Всего наилучшего в вашем путешествии!
1
Muhammed Jaseem
8 Май 2021 в 23:39
Лично я нахожу исходный код Python более легким для чтения, когда он разделен на четыре пробела. Итак, вот ваша функция снова с более широким отступом:
def count_letter(mylist):
count = 0
for i in range(len(mylist)):
if letter in i:
count += 1
a_list.append(i)
return a_list
print(len(a_list))
for i in range(...)
будет перебирать набор целых чисел. Таким образом, i
будет принимать новое целочисленное значение для каждой итерации цикла. Сначала i
будет 0
, затем 1
на следующей итерации и так далее.
Затем вы спрашиваете if letter in i:
. Это никогда не может быть правдой. letter
— это строка, а i
— целое число. Строка никогда не может быть «внутри» целого числа, поэтому этот оператор if никогда не будет выполняться. Скорее, вы хотите проверить, находится ли letter
в текущем слове (i
-е слово в списке). Оператор if должен читать:
if letter in mylist[i]:
...
Где mylist[i]
— текущее слово.
Затем вы увеличиваете count
и добавляете i
к a_list
. Вероятно, вы хотели добавить mylist[i]
к a_list
, но я не понимаю, зачем вам вообще нужно a_list
. Вам просто нужно count
, так как это отслеживает, сколько слов вы встретили до сих пор, для которых условие истинно. count
также является переменной, которую вы должны вернуть в конце, так как это цель функции: вернуть количество слов (а не самих слов), которые содержат определенную букву.
Кроме того, отступ последнего оператора print
делает его частью тела функции. Однако это после return
, что означает, что у него никогда не будет возможности напечатать. Когда вы используете return
внутри функции, она завершает функцию, и поток выполнения возвращается к тому месту, из которого функция была первоначально вызвана.
Последнее изменение, которое необходимо применить, заключается в том, что ваша функция должна принимать букву для поиска в качестве параметра. Сейчас ваша функция принимает только один параметр — список слов, по которым нужно искать.
Вот изменения, которые я бы применил к вашему коду:
def count_letter(words, letter): # I find 'words' is a better name than 'mylist'.
count = 0
for i in range(len(words)):
current_word = words[i]
if letter in current_word:
count += 1
return count
Вот как вы можете использовать эту функцию:
words = ["hello", "world", "apple", "sauce"]
letter = "e"
count = count_letter(words, letter)
print("The letter '{}' appeared in {} words.".format(letter, count))
Выход:
The letter 'e' appeared in 3 words.
1
Paul M.
8 Май 2021 в 23:49
Я думаю, что «принимает» означает, что функция должна быть определена с двумя параметрами: words_list и letter:
def count_letter(words_list, letter):
Алгоритм на естественном языке может быть таким: дайте мне сумму слов, где буква присутствует для каждого слова в списке слов.
В Python это может быть выражено как:
def count_letter(words_list, letter):
return sum(letter in word for word in words_list)
Некоторое объяснение: letter in word
возвращает логическое значение (True или False), а в Python логические значения являются подклассом целого числа (True равно 1, а False равно 0). Если буква есть в слове, результат будет 1, а если нет, то 0. Подведение итогов дает количество слов, в которых присутствует буква.
1
Aivar Paalberg
8 Май 2021 в 23:53
Я прочитал все ваши ответы, некоторые важные моменты я записал, сегодня снова сидел со своим кодом, и после еще нескольких попыток он сработал… Итак, окончательный вариант выглядит так:
words = ['fortran', 'basic', 'java', 'python', 'c++']
letter = "a"
def count_letter(words, letter):
count = 0
for word in words:
if letter in word:
count += 1
return count
print(count_letter((words),letter))
Ответ системы: 3
Что для меня пока не очевидно: правильные отступы (они тоже были частью проблемы), и дополнительная пара скобок вокруг words
в строке print
. Но это приходит с обучением.
Спасибо еще раз!
Detailed Info
- Spaces0
- Newlines0
- Letters (without Space & Newline)0
- Average Words in a Sentence0
Configure items
-
Font size
-
Download as .txt
Download
-
Share me →
What is a Word?
A word is a combination of letters that may or may not have meaning. Usually, words are separated by spaces, hyphens, punctuation marks, and so on.
What is a character?
Any visible or non-visible item is defined as a character, as you may know, that Google Docs doesn’t count new-line as a character.
What is a sentence?
A sentence is a combination of many words and ends with a full stop or a punctuation mark.
What is a paragraph?
A paragraph is a collection of many sentences and ends with a new-line character.
What is a word counter or character counter?
It’s an online tool to count the number of characters, words, sentences, or paragraphs present in a given text.
How many words is one page ?
1 Page = 500words
Notes:- No of words on a page is basically based on the following requirements, Page format (A1-A5 or Letter), Font & Font size, Line spacing (1, 1.15, 1.5, 2, etc), and 4 margin space of a page.
Character count details in our character counting tool?
Character count (Topbar): Every typing character is included.
Character count without space: Character Count — Space Count => All Letters count without space.
Character count with space: This count is same as the total character count showing.
Why letter count or word count tool is essential?
As you may know, most social media platforms have character limits in the number of letters they can be posted (twitter character limit is 280). Similarly, even if we are writing blogs, reviews, essays, novels, books, and so on, we may come across word limits in it, that’s why we have created this free online tool to assist with the information you need.
One important aspect of letter counter is that many websites provide similar facilities and our MS word, Google Docs all are also providing the same facility. Since these applications are not readily available. You can use our facilities to know the details.
Social networksCharacters
- Facebook250
- Twitter280
- Pinterest500
- Youtube70
- LinkedIn2000
Other itemsWords
- Holy Bible~ 700,000
- Game of Thrones~ 300,00
- Short stories~ 7,500
- Essays300–1,500
- Blogs500–1,000
Characters 0 Words 0 Lines 0
Character Counter is a 100% free online character count calculator that’s simple to use. Sometimes users prefer simplicity over all of the detailed writing information Word Counter provides, and this is exactly what this tool offers. It displays character count and word count which is often the only information a person needs to know about their writing. Best of all, you receive the needed information at a lightning fast speed.
To find out the word and character count of your writing, simply copy and paste text into the tool or write directly into the text area. Once done, the free online tool will display both counts for the text that’s been inserted. This can be useful in many instances, but it can be especially helpful when you are writing for something that has a character minimum or limit.
Character and word limits are quite common these days on the Internet. The one that most people are likely aware of is the 140 character limit for tweets on Twitter, but character limits aren’t restricted to Twitter. There are limits for text messages (SMS), Yelp reviews, Facebook posts, Pinterest pins, Reddit titles and comments, eBay titles and descriptions as well as many others. Knowing these limits, as well as being able to see as you approach them, will enable you to better express yourself within the imposed limits.
For students, there are usually limits or minimums for homework assignments. The same is often true for college applications. Abiding by these can have a major impact on how this writing is graded and reviewed, and it shows whether or not you’re able to follow basic directions. Character counter can make sure you don’t accidentally go over limits or fail to meet minimums that can be detrimental to these assignments.
This information can also be quite helpful for writers. Knowing the number of words and characters can help writers better understand the length of their writing, and work to display the pages of their writing in a specific way. For those who write for magazines and newspapers where there is limited space, knowing these counts can help the writer get the most information into that limited space.
For job seekers, knowing the number of characters of your resume can be essential to get all the information you want onto a single page. You can fool around with different fonts, their sizes and spacing to adjust the number of characters you can fit on a single page, but it’s important to know the number you’re attempting to fit on the page.
Character Counter isn’t only for English. The tool can be helpful for those writing in non-English languages where character count is important. This can be the case for languages Japanese, Korean, Chinese and many others where characters are the basis of the written language. Even for those who aren’t writing in English, knowing the character count of the writing is often beneficial to the writing.
Show word count
Word counts the number of words in a document while you type. Word also counts pages, paragraphs, lines, and characters.
When you need to know how many words, pages, characters, paragraphs, or lines are in a document, check the status bar.
For a partial word count, select the words you want to count. The status bar shows the word count for that selection and for the entire document.
Tip: Find the number of characters, paragraphs, and lines by clicking on the word count in the status bar.
Count the number of characters, lines, and paragraphs
You can view the number of characters, lines, paragraphs, and other information in your Word for Mac, by clicking the word count in the status bar to open the Word Count box. Unless you have selected some text, Word counts all text in the document, as well as the characters, and displays them in the Word Count box as the Statistics.
Count the number of words in a part of a document
To count the number of words in only part of your document, select the text you want to count. Then on the Tools menu, click Word Count.
Just like the Word desktop program, Word for the web counts words while you type.
If you don’t see the word count at the bottom of the window, make sure you’re in Editing view (click Edit Document > Edit in Word for the web).
Click the word count to switch it off and on.
Maybe you noticed that Word for the web gives you an approximate word count. That’s because it doesn’t count words in areas like text boxes, headers, footers, and SmartArt graphics. If you need an exact count, click Open in Word, and look at the word count at the bottom of the Word document window.
Need more help?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.