Python单词计数器对单词是否被引号括起来敏感?

标签 python string python-3.x counter

我的 Python 程序有问题。我正在尝试制作一个单词计数器,来自 Exercism 的练习.

现在,我的程序必须通过 13 项测试,所有测试都是带有空格、字符、数字等的不同字符串。 我曾经遇到一个问题,因为我会用空格替换所有非字母和非数字。这给 "don't" 这样的词带来了问题,因为它会将其分为两个字符串,dont。为了解决这个问题,我添加了一个 if 语句,排除单个 ' 标记被替换,这有效。

但是,我必须测试的字符串之一是“Joe can't Tell Between 'large' and large.”。问题是,由于我排除了 ' 市场,因此这里 large'large' 被视为两个不同的事物,而且它们是同一个词。如何告诉我的程序“删除”单词周围的引号?

这是我的代码,我添加了两种情况,一种是上面的字符串,另一种是另一个只有一个 ' 标记的字符串,您不应删除:

def word_count(phrase):
    count = {}
    for c in phrase:
        if not c.isalpha() and not c.isdigit() and c != "'":
            phrase = phrase.replace(c, " ")
    for word in phrase.lower().split():
        if word not in count:
            count[word] = 1
        else:
            count[word] += 1
    return count

print(word_count("Joe can't tell between 'large' and large."))
print(word_count("Don't delete that single quote!"))

感谢您的帮助。

最佳答案

模块string包含一些不错的文本常量 - 对您来说重要的是标点符号。模块collections holds Counter - 用于计算事物的专门字典类:

from collections import Counter 
from string import punctuation

# lookup in set is fastest 
ps = set(string.punctuation)  # "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~

def cleanSplitString(s):
    """cleans all punctualtion from the string s and returns split words."""
    return ''.join([m for m in s if m not in ps]).lower().split()

def word_count(sentence):
    return dict(Counter(cleanSplitString(sentence))) # return a "normal" dict

print(word_count("Joe can't tell between 'large' and large.")) 
print(word_count("Don't delete that single quote!"))

输出:

{'joe': 1, 'cant': 1, 'tell': 1, 'between': 1, 'large': 2, 'and': 1}
{'dont': 1, 'delete': 1, 'that': 1, 'single': 1, 'quote': 1}

如果您想将标点符号保留在单词中,请使用:

def cleanSplitString_2(s):
    """Cleans all punctuations from start and end of words, keeps them if inside."""
    return [w.strip(punctuation) for w in s.lower().split()] 

输出:

{'joe': 1, "can't": 1, 'tell': 1, 'between': 1, 'large': 2, 'and': 1}
{"don't": 1, 'delete': 1, 'that': 1, 'single': 1, 'quote': 1} 

Readup on strip()

关于Python单词计数器对单词是否被引号括起来敏感?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53016862/

相关文章:

c++ - 关于 map::erase 和 map::count

python-3.x - 当 pymongo 游标的所有元素都被迭代后,它会发生什么?

python - 如何从两个1D数组生成2D网格并将其转换为数据帧?

javascript - 检查字符串的第一个字符是否为数字会报错,表明 charat 不是有效方法

java - 从字符串中获取除最后一个单词以外的每个单词的最简单方法

python - 实现 python 元类来更改类级别变量

python - “jupyter notebook”命令在 Linux 上不起作用

javascript - 使用ajax将值从javascript传递到python

python - 使用Python计算坡度的程序

python - 使用 pandas 在 csv 文件的同一行上用下一列的值填充一行中的空值