Reputation:
I am trying to count the number of words in a string including the punctuation (,/;/./!/?).
So far have been able to to count only the number of words but the punctuation are not getting counted. Tried giving a space before each punctuation using replace but it still is not getting counted. Can someone help me out?
My code:
import re
input_text = input("Enter the data: ")
final_text = input_text.replace(',',' ,').replace(';',' ;').replace('.',' .').replace('?',' ?').replace('!',' !')
count = len(re.findall(r'\w+', final_text))
print(count)
e.g. for this input
hi. how are you? I am good! what about you? bye!
It should be 16 including all punctuation. But I am getting only 11.
Upvotes: 1
Views: 1583
Reputation: 92854
Use the following approach:
s = "hi. how are you? I am good! what about you? bye!"
result = len(re.findall(r'[^\w\s]|\w+', s))
print(result) # 16
\w+
- will match alphanumeric sequences(including underscore _
)
[^\w\s]
- will match all characters except alphanumeric and whitespaces
Upvotes: 2
Reputation: 4330
a simple solution to your problem without any imports:
my_string = "hi. how are you? I am good! what about you? bye!"
space_words = my_string.strip().split(" ")
count = len(space_words)
for word in space_words:
for character in word:
if not character.isalpha():
count += 1
print count
Output:
16
Upvotes: 0