如何在PYTHON中查找段落(不包括空格)中的总字符数?

时间:2017-10-13 14:24:55

标签: python python-3.x

使用split命令查找段落中的总词数很容易但是在使用PYTHON查找段落中的字符数时该怎么办?

7 个答案:

答案 0 :(得分:2)

我会去列表理解:

len([c for c in "la a a" if c not in (' ', '\n') ])

答案 1 :(得分:2)

有很多方法可以做到这一点,所以我想知道他们如何相互公平,所以我给他们计时。我实现了此问题中的所有方法以及here中的任何其他方法。

from timeit import timeit

setup = """
from collections import Counter
import string

text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In malesuada eget tortor vel tempor. Cras condimentum risus a mi sagittis, at lobortis dui efficitur. Suspendisse fringilla ligula at eros consequat aliquet. Praesent volutpat sapien non aliquam cursus. Suspendisse auctor sapien ac leo luctus scelerisque. Cras eget fringilla mauris. Vivamus fermentum, nisl et mollis consequat, nisl sapien lacinia ex, ac finibus eros dui vel sapien. Curabitur dignissim porttitor ex sed vestibulum. Nullam nulla lorem, aliquam in turpis at, egestas tempor turpis. Aenean at lorem molestie, placerat eros in, tempus dui. Morbi magna nulla, blandit ac vestibulum faucibus, luctus sit amet libero. Ut quis lorem porta, cursus nunc id, malesuada mauris. Aenean luctus diam ac tortor rutrum mattis. Donec ultrices nibh quis est varius pellentesque. Donec tempor, est vel commodo ultricies, mauris tortor egestas orci, ut hendrerit orci ex eget risus. In eu ullamcorper odio, lacinia auctor urna.'

def split_join(s):
    return len(''.join(s.split()))

def list_comprehension(s):
    return len([c for c in s if c != " "])

def sum_len_split(s):
    return sum([len(x) for x in s.split()])

def map_len_split(s):
    return sum(map(len, s.split()))

def conventional_loop(s):
    x = 0
    for n in s:
        if not n.isspace():
            x += 1
    return x

def replace_space(s):
    return len(s.replace(" ", ""))

def counter(s):
    valid_letters = string.ascii_letters
    count = Counter(s)
    return sum(count[letter] for letter in valid_letters)

def discount_space(s):
    return len(s) - s.count(" ")
"""    

functions = [line[4:-4] for line in setup.split('\n')
             if line.startswith('def ')]

n = 100000
results = []
for function in functions:
    results.append((timeit('{}(text)'.format(function), setup=setup, number=n), function))
results.sort()

for time, function in results:
    print(function, time)

结果

discount_space 0.1687837346025738
replace_space 0.5508266038467227
split_join 1.231192897388388
map_len_split 1.5719588628305754
sum_len_split 2.2983778970212896
list_comprehension 5.715995796916212
counter 7.133700537385263
conventional_loop 11.01061941802605

当然,除非你的字符串中有数百万个字符,否则性能不是问题,代码清晰度更重要。在那种情况下,我仍然认为discount_space()是最明确和直接的。

答案 2 :(得分:0)

from collections import Counter
import string

def count_letters(word, valid_letters=string.ascii_letters):
    count = Counter(word) # this counts all the letters
    return sum(count[letter] for letter in valid_letters) # valid letters

答案 3 :(得分:0)

您可以拆分字符串(删除空格并给出字符串列表),然后计算每个单词的字符数并总计。

myString = "Hello you !" # 11 characters

totalNCharacters = sum([len(x) for x in mystring.split()]) 

print(totalCharacters) # output: 9

答案 4 :(得分:0)

字符,我假设任何不是空白的意思,包括标点符号。这是可以做到的一种方式:

#!/usr/bin/python

s = 'abc  def   ghi....\n":)*9.w wer'
x = 0
for n in s:
    if not n.isspace():
        x += 1

print("total number of characters is {}".format(x))

答案 5 :(得分:0)

paragraph = "The quick brown fox jumps over the lazy dog"

删除空格并打印长度:

print(len(paragraph.replace(" ", "")))
# 35

答案 6 :(得分:0)

我会使用拆分加入

def char_count(s):
    return len(''.join(s.split()))