2017-03-25 42 views
1

我想计算包括标点符号(,/; /./!/?)在内的字符串数量。计算包括标点符号在内的字数

到目前为止,已经能够仅计算单词的数量,但标点符号未被计数。试图在每个标点符号之前使用替换来给出空格,但它仍然没有被计算。有人可以帮我吗?

我的代码:

import re 
    input_text = input("Enter the data: ") 
    final_text = input_text.replace(',',' ,').replace(';',' ;').replace('.',' .').replace('?',' ?').replace('!',' !')  
    count = len(re.findall(r'\w+', final_text)) 
    print(count) 

例如对于此输入

嗨。你好吗?我很好!你呢?再见!

它应该是16包括所有标点符号。但我只得到11

+0

算的话,然后计算标点符号?把它们加起来? – dgg32

+0

你的代码片段中的ident是奇数。 – dgg32

+0

@ dgg32纠正!感谢您指出!是的,把它们加起来很好! –

回答

3

用下面的办法:

s = "hi. how are you? I am good! what about you? bye!" 
result = len(re.findall(r'[^\w\s]|\w+', s)) 

print(result) # 16 

\w+ - 将匹配的字母数字序列(包括下划线_

[^\w\s] - 将匹配除了字母数字的所有字符和空格

+0

工程就像一个魅力!谢谢 ! –

+1

@ phoenix_9,不客气 – RomanPerekhrest

0

一个简单的解决问题的方法没有任何进口:

my_string = "hi. how are you? I am good! what about you? bye!" 
space_words = my_string.strip().split(" ") 
count = len(space_words) 
for word in space_words: 
    for character in word: 
     if not character.isalpha(): 
      count += 1 
print count 

输出:

+0

这是不安全的,因为它假定每个单词只有一个标点符号。缩写像例如或者即将打破它,西班牙问号也会失败:¿阙?那么如果这个词包含一个数字,比如deadmau5呢?米里亚姆的回答更安全。 –

相关问题