我的Python程序有问题。我正在努力反驳,这是锻炼主义的一种作法。
现在,我的程序必须通过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!"))
谢谢您的帮助。
使用.strip()
起飞的第一个和最后一个字符,一旦你在列表中有他们- https://python-reference.readthedocs.io/en/latest/docs/str/strip.html
def word_count(phrase):
count = {}
for c in phrase:
if not c.isalpha() and not c.isdigit() and c != "'":
phrase = phrase.replace(c, " ")
print(phrase)
for word in phrase.lower().split():
word = word.strip("\'")
if word not in count:
count[word] = 1
else:
count[word] += 1
return count
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句