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

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

问题描述

所以我已经学习Python几个月了,想知道我将如何编写一个函数来计算一个单词在一个句子中出现的次数.如果有人可以给我逐步的方法,我将不胜感激.

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.

推荐答案

快速解答:

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

'某些string.split()会将空格上的字符串(空格,制表符和换行符)拆分为单词类事物的列表.然后 ['some','string'].count(item)返回列表中 item 出现的次数.

'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.

这不能消除标点符号.您可以使用 string.maketrans 做到这一点和 str.translate .

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)

这里的关键是我们构造了字符串 delete ,以便它包含除字母,数字和空格之外的所有ascii字符.然后,在这种情况下, str.translate 使用一个转换表,该表不更改字符串,但不删除字符串.

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天全站免登陆