我的 Python 程序有问题。我正在尝试制作一个单词计数器,来自 Exercism 的练习.
现在,我的程序必须通过 13 项测试,所有测试都是带有空格、字符、数字等的不同字符串。
我曾经遇到一个问题,因为我会用空格替换所有非字母和非数字。这给 "don't"
这样的词带来了问题,因为它会将其分为两个字符串,don
和 t
。为了解决这个问题,我添加了一个 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}
关于Python单词计数器对单词是否被引号括起来敏感?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53016862/