我是个新手,所以如果我问一些已经得到答案的问题,请原谅我,但请相信我,我确实在寻找答案,但没有找到。在
我有一个任务要计算给定的文本中有多少个给定的单词。单词可以是一个洞,也可以是另一个单词的一部分。字母大小写无关紧要。如果单词在文本中出现几次,则只应计算一次。 到目前为止,我终于做到了:
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,因为有香蕉和香蕉,相似但不同。在
提前谢谢。在
你的代码有部分错误。试试这个:
但这只在Python2.7中有效,所以如果您使用Python3+的话,您需要将最后的
print
更改为print(count)
。在使用^{} 和生成器表达式,这似乎是最简单的解决方案:
First-string是不可变的,因此},而是返回new instance-小写。另一个问题是
text.lower()
本身没有改变{if a in base
检查是否存在,而不知道有多少次。。。在相关问题 更多 >
编程相关推荐