删除标点符号并创建字典 Python

Removing punctuation and creating a dictionary Python

我正在尝试创建一个函数来删除标点符号并将字符串中的每个字母小写。然后,它应该 return 所有这些都以字典的形式出现,计算字符串中的词频。

这是我到目前为止写的代码:

def word_dic(string):
    string = string.lower()
    new_string = string.split(' ')
    result = {}

    for key in new_string:
        if key in result:
            result[key] += 1
        else:
            result[key] = 1

    for c in result:
        "".join([ c if not c.isalpha() else "" for c in result])

    return result

但这是我执行后得到的结果:

{'am': 3,
 'god!': 1,
 'god.': 1,
 'i': 2,
 'i?': 1,
 'thanks': 1,
 'to': 1,
 'who': 2}

我只需要去掉词尾的标点符号即可。

"".join([ c if not c.isalpha() else "" for c in result]) 创建一个没有标点符号的新字符串,但它不会 任何事情;它会立即被丢弃,因为您永远不会存储结果。

真的,做到这一点的最好方法是在 将它们计入 result 之前规范化您的密钥 。例如,您可以这样做:

for key in new_string:
    # Keep only the alphabetic parts of each key, and replace key for future use
    key = "".join([c for c in key if c.isalpha()])
    if key in result:
        result[key] += 1
    else:
        result[key] = 1

现在 result 从来没有带标点符号的键(并且 "god.""god!" 的计数仅在键 "god" 下求和),并且不需要另一次删除标点符号。

或者,如果您只关心每个单词的前导和尾随标点符号(因此 "it's" 应按原样保留,而不是转换为 "its"),则可以进一步简化。只需 import string,然后更改:

    key = "".join([c for c in key if c.isalpha()])

至:

    key = key.rstrip(string.punctuation)

这与您在问题中的具体要求相符(删除单词末尾的标点符号,但不删除单词开头或嵌入单词中的标点符号)。

另一种选择是使用著名的 Python 的 batteries included

>>> sentence = 'Is this a test? It could be!'
>>> from collections import Counter
>>> Counter(re.sub('\W', ' ', sentence.lower()).split())
Counter({'a': 1, 'be': 1, 'this': 1, 'is': 1, 'it': 1, 'test': 1, 'could': 1})

利用 collections.Counter for counting words, and re.sub 替换所有非单词字符。

您可以使用 string.punctuation 来识别标点符号,并在正确分解字符串后使用 collections.Counter 来计算出现次数。

from collections import Counter
from string import punctuation

line = "It's a test and it's a good ol' one."

Counter(word.strip(punctuation) for word in line.casefold().split())
# Counter({"it's": 2, 'a': 2, 'test': 1, 'and': 1, 'good': 1, 'ol': 1, 'one': 1})

使用 str.strip 而不是 str.replace 可以保留诸如 It's.

之类的词

方法 str.casefold 只是 str.lower 的更一般情况。

也许如果您想稍后重复使用这些词,您可以将它们连同出现次数一起存储在 sub-dictionary 中。每个单词都会在字典中占有一席之地。我们可以创建自己的函数来删除标点符号,非常简单。 查看下面的代码是否满足您的需求:

def remove_punctuation(word):
    for c in word:
        if not c.isalpha():
            word = word.replace(c, '')
    return word


def word_dic(s):
    words = s.lower().split(' ')
    result = {}

    for word in words:
        word = remove_punctuation(word)

        if not result.get(word, None):
            result[word] = {
                'word': word,
                'ocurrences': 1,
            }
            continue
        result[word]['ocurrences'] += 1  

    return result


phrase = 'Who am I and who are you? Are we gods? Gods are we? We are what we are!'
print(word_dic(phrase))

你会得到这样的输出:

{ 'who': { 'word': 'who', 'ocurrences': 2}, 'am': { 'word': 'am', 'ocurrences': 1}, 'i': { 'word': 'i', 'ocurrences': 1}, 'and': { 'word': 'and', 'ocurrences': 1}, 'are': { 'word': 'are', 'ocurrences': 5}, 'you': { 'word': 'you', 'ocurrences': 1}, 'we': { 'word': 'we', 'ocurrences': 4}, 'gods': { 'word': 'gods', 'ocurrences': 2}, 'what': { 'word': 'what', 'ocurrences': 1} }

然后您可以轻松访问每个单词及其出现,只需执行以下操作:

word_dict(phrase)['are']['word']       # output: are
word_dict(phrase)['are']['ocurrences'] # output: 5