Home > OS >  count words from three texts
count words from three texts

Time:10-28

I must count the number of words in three texts.

text1 = "There was no reason to believe that a young black boy at this time,
in this place, could in any way alter history."

text2 = "Bioinformatics can be considered as the application of computer
technology to the understanding and effective use of biological and clinical data."

text3 = "Drug discovery and development pipelines are long, complex and depend
on numerous factors."

I must use something like this:

def count_words(text):

    num_words = 0

---Hier i must place the code---

    return num_words

to then apply this:

    num_words = count_words(text1)
    print("Text 1")
    print("The word number is %d" % num_words)


    num_words = count_words(text2)
    print("Text 2")
    print("The word number is %d" % num_words)


    num_words = count_words(text3)
    print("Text 3")
    print("The word number is %d" % num_words)

¿How to do it?

CodePudding user response:

you can do it like this:

>>> import string
>>> def count_words(text):
...     for punc in string.punctuation:
...             text = text.replace(punc, "")
...     return len(text.split())
... 
>>> num_words = count_words(text1)
>>> print("Text 1")
Text 1
>>> print("The word number is %d" % num_words)
The word number is 22
>>> 

we have replaced the punctuation marks with empty string in order to avoid them in counting in any sort of text where there are surrounded by spaces on both sides.

CodePudding user response:

Easiest way to do so with few lines of code.

def count_words(text): #text is your argument, i.e., your sentence
print(text)
print("The word number is %d" %len(text.split()))

To use it:

text1 = 'There was no reason to believe that a young black boy at this time,in this place, could in any way alter history'
count_words('text1')

CodePudding user response:

def count_words(text):

    num_words = 0
    num_words = len(text.split())
    return num_words
  • Related