Jump to content

Applied Programming/Strings/Python3

From Wikiversity

strings.py

[edit | edit source]
"""This program counts words in entered strings.

Input:
    Text string

Output:
    Word count

Example:
    Enter a string or press <Enter> to quit:
     The cat in the hat.
    You entered 5 words.

    Enter a string or press <Enter> to quit:
    ...

References:
    None

"""

import sys

def get_text():
    """Gets text string.

    Args:
        None

    Returns:
        string: Text string entered or None if no string entered.

    """
    print("Enter a string or press <Enter> to quit:")
    text = input()
    if text == "":
        return None
    else:
        return text


def count_words(text):
    """Counts words in text.

    Args:
        text (string): text with words to be counted.

    Returns:
        integer: Count of words in text.

    """
    SEPARATORS = " ~`!@#$%^&*()-_=+{}[]|\\:;""'<>,.?/"
    word_count = 0
    in_word = False
    for i in range(0, len(text)):
        if not in_word and text[i] not in SEPARATORS:
            word_count += 1
            in_word = True
        elif in_word and text[i] in SEPARATORS:
            in_word = False
    return word_count


def slice_first_word(text):
    """Removes the first word in text.

    Args:
        text (string): text with words.

    Returns:
        sliced_text (string): Text with the first word removed.

    """
    SEPARATORS = " ~`!@#$%^&*()-_=+{}[]|\\:;""'<>,.?/"
    index = 0

    for i in range(len(text)):
        if text[i] in SEPARATORS:
            break
        else: index += 1

    sliced_text = text[(index + 1):(len(text))]
    return sliced_text
    
    
def main():
    """Runs the main program logic."""

    try:
        while True:
            text = get_text()
            if text == None:
                break
            print(f"You entered {count_words(text)} words.\n")
            print("Here is your string with the first word sliced:\n")
            print(slice_first_word(text))
    except:
        print("Unexpected error.")
        print("Error:", sys.exc_info()[1])
        print("File: ", sys.exc_info()[2].tb_frame.f_code.co_filename) 
        print("Line: ", sys.exc_info()[2].tb_lineno)


main()

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.

See Also

[edit | edit source]