我如何计算一个单词在一个句子中出现的次数? (蟒蛇) [英] How do I calculate the number of times a word occurs in a sentence? (Python)

查看:125
本文介绍了我如何计算一个单词在一个句子中出现的次数? (蟒蛇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我现在一直在学习Python几个月,并想知道如何去写一个函数来计算一个单词在一个句子中出现的次数。如果有人可以请给我一个循序渐进的做法,我将不胜感激



谢谢



  def count_occurrences(word,sentence):
返回句子.lower().split().count(word)

'一些string.split()会将字符串分割成空白字符(空格,制表符和换行符)。然后 ['some','string']。count(item)返回项目出现在列表。



这不处理删除标点符号。你可以使用 string.maketrans str.translate

 #让字符集合保持(不要翻译它们)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep,keep)
delete =''.join(set(string.printable ) - set(keep))

def count_occurrences(word,sentence):
return sentence.lower()。translate(table,delete).split()。count(word)

这里的关键是我们已经构造了字符串 delete ,以便它包含除字母,数字和空格以外的所有ASCII字符。然后,在这种情况下, str.translate 需要一个不会更改字符串的转换表,但也会删除一串字符。

So I've been learning Python for some months now and was wondering how I would go about writing a function that will count the number of times a word occurs in a sentence. I would appreciate if someone could please give me a step-by-step method for doing this

Thank you

解决方案

Quick answer:

def count_occurrences(word, sentence):
    return sentence.lower().split().count(word)

'some string.split() will split the string on whitespace (spaces, tabs and linefeeds) into a list of word-ish things. Then ['some', 'string'].count(item) returns the number of times item occurs in the list.

That doesn't handle removing punctuation. You could do that using string.maketrans and str.translate.

# Make collection of chars to keep (don't translate them)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep, keep)
delete = ''.join(set(string.printable) - set(keep))

def count_occurrences(word, sentence):
    return sentence.lower().translate(table, delete).split().count(word)

The key here is that we've constructed the string delete so that it contains all the ascii characters except letters, numbers and spaces. Then str.translate in this case takes a translation table that doesn't change the string, but also a string of chars to strip out.

这篇关于我如何计算一个单词在一个句子中出现的次数? (蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆