创建一个计算单词和字符的函数(包括标点符号,但不包括空格)

问题描述 投票:1回答:4

我需要创建一个函数来计算给定短语中的字符数(包括标点符号和排除空格)和单词。到目前为止,我已经创建了一个可以计算字符数的函数,但它也包含空格,并且不计算单词。如何排除空格并实现计数单词呢?

text = " If I compare myself to someone else, then I am playing a game 
I will never win. "
def count_chars_words(txt):
    chars = len(txt.replace(' ',''))
    words = len(txt.split(' '))
    return [words,chars]

print(count_chars_words(text))


output [19, 63]
python
4个回答
1
投票

通过使用replace(' ','')从文本中删除空格来计算字符,然后获取字符串的长度。

通过将句子分成单词列表并检查列表的长度来计算单词。

然后,在列表中返回两者。

text ="If I compare myself to someone else, then I am playing a game I will never win."
def count_chars_words(txt):
        chars = len(txt.replace(' ',''))
        words = len(txt.split(' '))
        return [words,chars]

print(count_chars_words(text))

输出:

[17, 63]

要了解replace()split()的作用:

>> text.replace(' ','')
'IfIcomparemyselftosomeoneelse,thenIamplayingagameIwillneverwin.'
>> text.split(' ')
['If', 'I', 'compare', 'myself', 'to', 'someone', 'else,', 'then', 'I', 'am', 'playing', 'a', 'game', 'I', 'will', 'never', 'win.']

0
投票

函数string.split()可能对您有用!它可以取一个字符串,找到你输入的任何内容的每个实例(例如" "),并将你的字符串拆分成由" "分隔的每组字符的列表(几乎是单词)。有了这个,你应该能够继续!

"If I compare myself to someone else, then I am playing a game I will never win.".split(" ")

['If', 'I', 'compare', 'myself', 'to', 'someone', 'else,', 'then', 'I', 'am', 'playing', 'a', 'game', 'I', 'will', 'never', 'win.']


0
投票

为了避免计算空格,您是否考虑过使用if语句?您可能会发现string.whitespacein运算符在这里很有用!

至于计算单词,string.split是你的朋友。事实上,如果你首先分开单词,是否有一种简单的方法可以避免上面引用的if


0
投票

这只是一个想法,而不是有效的方法,如果你需要一个好方法来使用正则表达式:

text ="If I compare myself to someone else, then I am playing a game I will never win."

total_num = len(text)
spaces = len([s for s in text if s == ' '])
words = len([w for w in text.split()])

print('total characters = ', total_num)
print('words = ', words)
print('spaces=', spaces)
print('charcters w/o spaces = ', total_num - spaces)

输出:

total characters =  79
words =  17
spaces= 16
charcters w/o spaces =  63

编辑:使用正则表达式将更有效:

import re

chars_without_spaces = re.findall(r'[^\s]', text)  # charcters w/o spaces 
words = re.findall(r'\b\w+', text)  # words
© www.soinside.com 2019 - 2024. All rights reserved.