【问题标题】:how to use count with a regex [duplicate]如何使用正则表达式计数[重复]
【发布时间】:2019-04-09 16:51:01
【问题描述】:

假设我有这个字符串

text = "microsoft,javascript java microsoft office"

如果我想计算 microsoft office 存在的次数

print(text.count("microsoft office")) # returns 1

但是如果我想计算java存在多少次,而不考虑javascript

print(text.count("java")) # returns 2 but it should return 1

我教过从 re 使用 split :

import re 
count = 0
text = "microsoft,javascript java microsoft office"
words = re.split("[ ,]", text)
for word in words:
    if word == "java":
        count += 1

print(count) # returns 1

它适用于java,但不适用于microsoft office,因为它会被空格分割并且不满足if条件if word == "microsoft"if word == "office"

我想要的是一种混合计数和拆分的方式,以适用于这两个示例

【问题讨论】:

    标签: python regex split count


    【解决方案1】:

    这可以使用正则表达式中的 findall 操作来完成,试试这个代码

    import re
    text = "microsoft,javascript java microsoft office"
    word = input("enter a word to check its occurence ")
    check = re.findall(word,text)
    print(word +" occured "+str(len(check))+ " times")
    

    【讨论】:

    • 它为 java 返回 2,因为有 javascript
    • 我理解这种情况,你只需要添加“java”后跟空格
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2017-11-23
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多