Python单词计数器对单词是否被引号包围敏感?
我的Python程序有问题。我正在试着做一个单词计数器,一个来自英语的练习 现在,我的程序必须通过13个测试,所有测试都是带有空格、字符、数字等的不同字符串。 我曾经遇到过一个问题,因为我会用空格替换所有非字母和非数字。这就产生了像Python单词计数器对单词是否被引号包围敏感?,python,string,python-3.x,counter,Python,String,Python 3.x,Counter,我的Python程序有问题。我正在试着做一个单词计数器,一个来自英语的练习 现在,我的程序必须通过13个测试,所有测试都是带有空格、字符、数字等的不同字符串。 我曾经遇到过一个问题,因为我会用空格替换所有非字母和非数字。这就产生了像“don”这样的词的问题,因为它会将它分成两个字符串,don和t。为了解决这个问题,我添加了一个if语句,排除了单个“标记被替换,这很有效 然而,我必须测试的字符串之一是“Joe无法区分‘大’和‘大’。。问题是,由于我排除了”市场,这里的大和大被视为两个不同的东西,它
“don”
这样的词的问题,因为它会将它分成两个字符串,don
和t
。为了解决这个问题,我添加了一个if
语句,排除了单个“
标记被替换,这很有效
然而,我必须测试的字符串之一是“Joe无法区分‘大’和‘大’。
。问题是,由于我排除了”
市场,这里的大
和大
被视为两个不同的东西,它们也是同一个词。我如何告诉我的程序“删除”单词周围的引号
这是我的代码,我添加了两个场景,一个是上面的字符串,另一个是只有一个“
标记的字符串,您不应该删除:
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()
删除它们-
该模块包含一些漂亮的文本常量-对您来说重要的是标点符号。模块-用于计算事物的专用字典类:
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!"))
如果要将标点符号保留在单词中,请使用:
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, 'cant': 1, 'tell': 1, 'between': 1, 'large': 2, 'and': 1}
{'dont': 1, 'delete': 1, 'that': 1, 'single': 1, 'quote': 1}
{'joe': 1, "can't": 1, 'tell': 1, 'between': 1, 'large': 2, 'and': 1}
{"don't": 1, 'delete': 1, 'that': 1, 'single': 1, 'quote': 1}
退房
{'joe': 1, "can't": 1, 'tell': 1, 'between': 1, 'large': 2, 'and': 1}
{"don't": 1, 'delete': 1, 'that': 1, 'single': 1, 'quote': 1}