python - 字符串中第一个字母的单词计数器不起作用
问题描述
我试图让 Python 中的计数器按第一个字母计算单词。我可以让它计算所有内容,包括空格。
例如,在下面的代码中,以 's' 开头的单词数为 4。我知道这一点,但我的程序给我的 's' 为 10,即字符串中的每个 's'。我怎样才能让它只使用单词中的第一个字母?
from collections import Counter
my_str = "When I pronounce the word Future,\n the first syllable already belongs to the past.\n\n When I pronounce the word Silence,\n I destroy it.\n\n When I pronounce the word Nothing,\n I make something no nonbeing can hold.\n\n Wislawa Szymborska"
my_count = Counter(my_str.lower())
for word in [my_str]:
my_count[word[0].lower()]+=1
print(my_count)
我的输出是:
Counter({' ': 37, 'e': 21, 'n': 19, 'o': 18, 't': 13, 'i': 12, 'h': 11, 'r': 11, 's': 10, 'w': 9, '\n': 9, 'a': 9, 'l': 8, 'd': 6, 'u': 5, 'c': 5, 'p': 4, 'y': 4, 'b': 4, 'g': 4, ',': 3, '.': 3, 'm': 3, 'f': 2, 'k': 2, 'z': 1})
解决方案
尝试这个:
from collections import Counter
from operator import itemgetter
my_str = "When I pronounce the word Future,\n the first syllable already belongs to the past.\n\n When I pronounce the word Silence,\n I destroy it.\n\n When I pronounce the word Nothing,\n I make something no nonbeing can hold.\n\n Wislawa Szymborska"
my_count = Counter(map(itemgetter(0), my_str.lower().split()))
print(my_count)
输出:
Counter({'w': 7, 'i': 6, 't': 6, 'p': 4, 's': 4, 'n': 3, 'f': 2, 'a': 1, 'b': 1, 'd': 1, 'm': 1, 'c': 1, 'h': 1})
推荐阅读
- python - 如何实现“tzinfo”以将当前 GMT 偏移到 EST(GMT -4:00)?
- openlayers - 如何修复“错误:无法为图层创建渲染器:未定义”?
- python-3.x - python json.dumps() 并将数据插入 mysql 1064 错误
- qt - 使用带有“父项:Overlay.overlay”的弹出窗口时的 QML 属性值传播
- javascript - Ionic/Firebase 图像选择器/裁剪和上传问题
- javascript - 使用 ng-change 函数更改变量的值
- ruby-on-rails - 访问类主体中的变量
- sql - 如何在 SQL 中创建特殊情况的 Intersect 子句?
- python - 为什么在循环中调用变量后会发生变化?
- function - Haskell中不同数据类型的函数