0

该问题要求编写一个函数来创建一个字典,其中包含字符串中每个单词的计数,并且只有在它是单词中的最后一个字符时才删除标点符号。我一直在尝试解决问题的标点部分。对于作业,我需要使用来识别标点符号isalpha,但是

  1. 我不确定使用word[-1]是否有助于识别最后一个字符是否是标点符号和
  2. 我不知道如何编写 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}
4

2 回答 2

1

一般来说,为了计算东西,你应该使用collections.Counter类,并检查一个元素是否是 a,或者?你应该使用string.punctuation包含它们的元素,例如:

import string
from collections import Counter
txt = "Why's it always the nice guys?"

counted = Counter(
    word if not word[-1] in string.punctuation else word[:-1] for word in txt.split()
)
print(counted)

>>> Counter({"Why's": 1, 'it': 1, 'always': 1, 'the': 1, 'nice': 1, 'guys': 1})

现在,如果您真的需要字典来输出,只需执行以下操作:

print(dict(counted))

>>> {"Why's": 1, 'it': 1, 'always': 1, 'the': 1, 'nice': 1, 'guys': 1}
于 2020-02-28T23:19:46.340 回答
0

您好,欢迎来到 SO。

如果我理解您的问题,我认为您只是以错误的方式编写了构造if then else

import string

def word_distribution(s):
    s = s.lower()
    s = s.split()
    wordfreq = {}
    for word in s:
        if word[-1] in string.punctuation:
            if word[-1] in wordfreq:
                wordfreq[word[:-1]] += 1 
            else:
                wordfreq[word[:-1]] = 1
        else:
            if word in wordfreq:
                wordfreq[word] += 1 
            else:
                wordfreq[word] = 1

    return wordfreq

x = word_distribution("Why's it always the nice guys?")
print(x) 

我曾经string.punctuation检查最后一个字符是否是标点符号。

输出是:{"why's": 1, 'it': 1, 'always': 1, 'the': 1, 'nice': 1, 'guys': 1}

编辑:另一个解决方案使用isalpha

def word_distribution(s):
    s = s.lower()
    s = s.split()
    wordfreq = {}
    for word in s:
        if word[-1].isalpha():
            if word[-1] in wordfreq:
                wordfreq[word] += 1 
            else:
                wordfreq[word] = 1
        else:
            if word in wordfreq:
                wordfreq[word[:-1]] += 1 
            else:
                wordfreq[word[:-1]] = 1

    return wordfreq

x = word_distribution("Why's it always the nice guys?")
print(x)

输出是:{"why's": 1, 'it': 1, 'always': 1, 'the': 1, 'nice': 1, 'guys': 1}

于 2020-02-28T23:06:58.063 回答