Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
removing spaces
#1
hello I have to calculate the arithmetic mean in the text (the number of letters divided by the number of sentences). The problem is that when counting letters, it also counts spaces and the result is spooky. How can I easily exclude joints from counting?
Text = input("give text: ")
characters = len(Text)
words = len(Text.split())
a = characters
b = words
division = a/b
print("words in this text hawe ", division, "characters")
Reply
#2
As with most things, there's more than one way to do this.

One way to count the number of 'words' from a input, is to convert said into a list, which is what I think that you are attempting with...
words = len(Text.split())
I would go one stage further and create a list object with which to work. Also, you've not specified a split separator.

This code...

text_input = input("Enter you text: ")

list_input = text_input.split(' ')

words = len(list_input)

print(f"Your input contains {words} words.")
... creates a list object from the user input and then simply outputs the length of that list as the number of words contained therein. What constitutes a 'word' is open to interpretation, but as a basic concept, this may be of help to you.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
This example joins all the words without spaces
words = input("Enter text: ").split()
print(len(''.join(words) / len(words))
This example sums the lengths of each word.
words = input("Enter text: ").split()
print(sum(map(len, words)) / len(words))
rob101 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing leading\trailing spaces azizrasul 8 2,700 Oct-23-2022, 11:06 PM
Last Post: azizrasul
  removing spaces/tabs after used .strip() zarize 0 1,597 Sep-11-2019, 12:46 PM
Last Post: zarize

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020