该问题要求编写一个函数来创建一个字典,其中包含字符串中每个单词的计数,并且只有在它是单词中的最后一个字符时才删除标点符号。我一直在尝试解决问题的标点部分。对于作业,我需要使用来识别标点符号isalpha
,但是
- 我不确定使用
word[-1]
是否有助于识别最后一个字符是否是标点符号和 - 我不知道如何编写 else 语句来生成完整的字典。
def word_distribution(s):
s = s.lower()
s = s.split()
wordfreq = {}
for word in s:
if word[-1].isalpha():
if word in wordfreq:
wordfreq[word] += 1
else:
wordfreq[word] = 1
return wordfreq
我的代码正在生成的示例...
word_distribution("Why's it always the nice guys?")
Out : {'always': 1, 'it': 1, 'nice': 1, 'the': 1}
它应该产生什么的例子......
Out : {'always': 1, 'it': 1, 'nice': 1, 'the': 1, 'why's': 1, 'guys': 1}