0

How can I split a string like "five 6 seven, eight!nine" to have only words? I mean remove everything and count the words? or in other words, how split a sentence with several delimiters? I should not use libraries.

def count_words(string):
    testlen=string.split( )
    
    return len(testlen)
Kris
  • 8,680
  • 4
  • 39
  • 67
Samin Ba
  • 13
  • 5
  • 1
    Does this answer your question? [Split string with multiple delimiters in Python](https://stackoverflow.com/questions/4998629/split-string-with-multiple-delimiters-in-python) – Expurple Dec 29 '21 at 13:29
  • What is a "library" here? A Python module that comes built-in with a normal Python installation, is that a library? – 9769953 Dec 29 '21 at 13:31
  • no, i should not use import, – Samin Ba Dec 29 '21 at 13:39

3 Answers3

0

I'm adding this solution, even though there are duplicate answers spotted, because you say

  1. Do not use any libraries (I assume even re is not allowed? )
  2. You don't know what are the delimiters that might come

Example:

 def count_words(string):
        def ch(char):
            return char if char.isalnum() else " "
        return [ch(c) for c in string].count(" ")

It just replaces any non-alpha numeric to a space and then count the spaces. May be not a super pythonic one!

Kris
  • 8,680
  • 4
  • 39
  • 67
  • it is not working for count_words("test3four") ,it return 0 which suppose be 2. – Samin Ba Dec 29 '21 at 15:24
  • well this idea was to consider only alphabets and numbers to be valid, so here its only 1. You should improvise the logic, as per your need. – Kris Dec 30 '21 at 04:48
0

I recommend Using re.split(). it is efficient and usually used method to split on multiple characters at once.

import re

string = "This, is a sample string"

print("initial string is : " + string) 

splitted_string = re.split(', |_|-|!', data)

I hope it can help. take a look at its documentation. https://docs.python.org/3/library/re.html

0
def count_words(string):
    alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," "]
    for l in string:
        if l not in alphabet:
            string = string.replace(l, " ")#replacing non alphabit with space
            string = string.replace("  ", " ")#in case of 2 spaces resulted, replacing them with 1 space
    testlen = string.split(" ")
    print(testlen)
    return len(testlen)


string = "five 6 seven, eight!nine"
count_words(string)
Feras Alfrih
  • 492
  • 3
  • 11