I'm trying to analyze the contents of a string. If it has a punctuation mixed in the word I want to replace them with spaces.
For example, If Johnny.Appleseed!is:a*good&farmer is entered as an input then it should say there are 6 words, but my code only sees it as 0 words. I'm not sure how to remove an incorrect character.
FYI: I'm using python 3, also I can't import any libraries
string = input("type something")
stringss = string.split()
for c in range(len(stringss)):
for d in stringss[c]:
if(stringss[c][d].isalnum != True):
#something that removes stringss[c][d]
total+=1
print("words: "+ str(total))
Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
Python Code:def word_count(str): counts = dict() words = str. split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog. '))
Instantiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array. Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.
How about using Counter from collections ?
import re
from collections import Counter
words = re.findall(r'\w+', string)
print (Counter(words))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With