简体   繁体   中英

How to check if a string contains specific characters in a list in Python?

I'd like to count the number of sentences in a string. The sentences are seperated by '.', '?' or '.': The 'text' variable in my file says. Congratulations! Today is your day. You're off to Great Places! You're off and away!

Yet, my program says that this sentence consist of only 2 sentences. I assume that this is because these characters aren't repeated (3x times a '.' and only once a '.')

How would I fix this in my code? Thanks in advance.

def number_of_sentences(text):

    count = 0
    special_characters = ['.', '!', '?']

    for char in special_characters:
        if char in text:
            count += 1
    print(count)
    return count

You can use sum and a comprehension using str.count :

sum(text.count(c) for c in special_characters)

This isn't the preferred approach. Using regex is more stable:

import re
len(re.findall(r'\.|\!|\?', test))

Although why not just use the str.split function. Each sentence is separated by a space as it is:

len(text.strip().split(' '))

Yet another option is to leverage True and False summing like 1 and 0

sum(c in special_characters for c in text)

Add an if statement

 def count_special_chars(text):
    count = 0
    special_characters = ['.', '!', '?']
    for x in text:
        if x in special_characters:
            count +=1
    print(count)
            
count_special_chars('hi!!!!')

Just do the other way.

for char in text:
        if char in special characters:
            count += 1

This is the same complexity since inclusion check is also O(n) for strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM