[英]Counting no of words including punctuation
我试图计算字符串中的单词数,包括标点符号(,/; /./!/?)。
到目前为止,只能计算单词的数量,但标点符号没有计算在内。 尝试在使用替换之前在每个标点符号之前给出一个空格,但仍然没有计算。 有人可以帮我吗?
我的代码:
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岁。
使用以下方法:
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]
- 将匹配除字母数字和空格之外的所有字符
没有任何导入的问题的简单解决方案:
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
输出:
16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.