前期回顾:
之前讲了count()和find()两个方法的语法,示例以及注意事项。
具体使用:
今天讲的是count的一个具体使用。
python如何在一个只有英文字符和空格的文本里找只有英文字符的单词?
针对这个问题,如果直接对文本字符串text使用count()方法将不会得到我们需要的answer。
例如:
text = "Hello world, welcome to the world of Python"
print(text.count("world")) # 输出:2
print(text.count("or")) # 输出:2
事实上,我们希望输出0,因为单词‘or’并未出现,但是单词‘world’刚好有‘or’子字符串,所以输出2.
那我们需要对它进行改进。
其实count()方法其实也可以对列表数据继续统计。这样我们的问题就迎刃而解了。
将text转换为列表数据,每一个元素是一个单词。
如下:
text = "Hello world, welcome to the world of Python"
text_list = text.split(" ")
print(text_list) #输出:['Hello', 'world,', 'welcome', 'to', 'the', 'world', 'of', 'Python']
在使用count()方法,
text = "Hello world, welcome to the world of Python"
text_list = text.split(" ")
print(text_list.count('or')) #输出:0
print(text_list.count('hello')) #输出:0
看上述例子我们发现
print(text_list.count('hello'))的输出还是0,我们想这是因为count方法会区分大小写导致的。
于是我继续进行改进。
text = "Hello world, welcome to the world of Python"
text=text.lower()#将字符串的每一个字符统一小写
text_list = text.split(" ")
print(text_list.count('or'))
print(text_list.count('hello'))
这里,我使用了一个lower()方法,将字符串的每一个字符统一小写。这样就可以满足需求了。当然如果将字符串的每一个字符统一大写(方法是upper()),都是一样的效果。
注意:到底要不要将字符串的每一个字符统一小写,看具体的需求,灵活运用。