Python计算给定tex中的单词数

2024-09-30 16:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个新手,所以如果我问一些已经得到答案的问题,请原谅我,但请相信我,我确实在寻找答案,但没有找到。在

我有一个任务要计算给定的文本中有多少个给定的单词。单词可以是一个洞,也可以是另一个单词的一部分。字母大小写无关紧要。如果单词在文本中出现几次,则只应计算一次。 到目前为止,我终于做到了:

def count_words(text, words):
    count = 0
    text = text.lower()
    for w in words:
        if w in text:
            count =+ 1

    print (count)

count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"})
count_words("Bananas, give me bananas!!!", {"banana", "bananas"})
count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
                       {"sum", "hamlet", "infinity", "anything"})

有了这个代码,我设法得到所有树文本的最终计数为1,只有第三个是可以的。在

在我看来,我的第一个问题是文本.下()什么也没做,我觉得应该降低所有案例。在

我的第二个问题是第一种情况下“are”在“aresjfhdskfhskd”中找不到,但在第三种情况下“sum”在“ipsum”中找到。这两个单词都是大单词的一部分,但第一个单词找不到,第二个单词是。 另外,在第二种情况下,结果应该是2,因为有香蕉和香蕉,相似但不同。在

提前谢谢。在


Tags: 答案textin文本youcount情况单词
3条回答

你的代码有部分错误。试试这个:

def count_words(text, words):
    count = 0
    lower_text = text.lower()
    for w in words:
        if w in lower_text:
            count += 1

    print count

count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"})
count_words("Bananas, give me bananas!!!", {"banana", "bananas"})
count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
                   {"sum", "hamlet", "infinity", "anything"})

但这只在Python2.7中有效,所以如果您使用Python3+的话,您需要将最后的print更改为print(count)。在

使用^{}和生成器表达式,这似乎是最简单的解决方案:

text = text.lower()
count = sum(word in text for word in words)
# bools are cast to ints (0, 1) here

First-string是不可变的,因此text.lower()本身没有改变{},而是返回new instance-小写。另一个问题是if a in base检查是否存在,而不知道有多少次。。。在

def count_words(text, words):
    count = 0
    lower_text = text.lower()
    for w in words:
        print w + " - " + str(lower_text.count(w))

print "1"
count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"})
print "2"
count_words("Bananas, give me bananas!!!", {"banana", "bananas"})
print "3"
count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
                   {"sum", "hamlet", "infinity", "anything"})

相关问题 更多 >