所以我正在尝试使用 python 实现计算句子中下一个字母的代码。 例如,
"""So I am trying to implement code that will count the next letter in a sentence, using
python"""
最常见的字母一个接一个
对于's'
- 'o':1
- 'e':1
对于'o'
- ' ' :1
- 'd':1
- '你':1
- 'n':1
我想你明白了
我已经写好了计算字母数的代码
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
如您所见,这只计算字母,而不计算下一个字母。有人可以帮助我解决这个问题吗?
请您参考如下方法:
from collections import Counter, defaultdict
counts = defaultdict(Counter)
s = """So I am trying to implement code that will count the next letter in a sentence, using
python""".lower()
for c1, c2 in zip(s, s[1:]):
counts[c1][c2] += 1
(除了更简单之外,这应该比 pault 的答案快得多,因为它不会为每个字母遍历字符串)
未在代码中命名的谷歌概念:
for c1, c2 in ...(即有两个变量的事实):元组拆包s[1:]:切片。基本上这是第一个字符后字符串的副本。
