【发布时间】:2019-03-31 16:40:04
【问题描述】:
我的 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!"))
感谢您的帮助。
【问题讨论】:
标签: python string python-3.x counter