我需要创建一个函数来计算给定短语中的字符数(包括标点符号和排除空格)和单词。到目前为止,我已经创建了一个可以计算字符数的函数,但它也包含空格,并且不计算单词。如何排除空格并实现计数单词呢?
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]
通过使用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.']
函数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.']
为了避免计算空格,您是否考虑过使用if
语句?您可能会发现string.whitespace
和in
运算符在这里很有用!
至于计算单词,string.split
是你的朋友。事实上,如果你首先分开单词,是否有一种简单的方法可以避免上面引用的if
?
这只是一个想法,而不是有效的方法,如果你需要一个好方法来使用正则表达式:
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