Skip to main content
 首页 » 编程设计

python之在字符串中查找短语

2025年05月04日40cmt

我正在尝试检查字符串中是否存在短语“purple cow”。 “purple”和“cow”之间必须至少有一个空格或标点符号; “紫牛”是 Not Acceptable 。我尝试了以下程序,但收到错误消息。

import string 
 
def findPC(string): 
 
    strLower = string.lower() 
 
    # remove 'purplecow' in strLower 
    strLowerB = strLower.replace('purplecow', '') 
    print(strLowerB) 
 
    strList = list(strLowerB) 
    print(strList) 
 
    # remove punctuation in strLowerB 
    punct = string.punctuation() 
    for char in strList: 
        if char in punct: 
            strList.replace(char, '') 
 
    # remove spaces in strLowerB 
    strLower.replace(' ', '') 
    print(strLower) 
 
    # look for 'purplecow' in strLowerB 
    return 'purplecow' in string 
 
 
print(findPC('The purple cow is soft and cuddly. purplecow. Purple^&*(^&$cow.')) 

错误信息:

Traceback (most recent call last):   File "C:/Python36/findPC.py", 
line 28, in <module> 
    print(findPC('The purple cow is soft and cuddly. purplecow. Purple^&*(^&$cow.'))   File "C:/Python36/findPC.py", line 15, in 
findPC 
    punct = string.punctuation() AttributeError: 'str' object has no attribute 'punctuation' 

请您参考如下方法:

代码中的错误源于您在两个地方使用了 string,它们的含义不同。我对您的代码进行了一些编辑,以使其按您预期的方式工作。

import string 
 
def findPC(input_string): 
 
    strLower = input_string.lower() 
 
    # remove 'purplecow' in strLower 
    strLowerB = strLower.replace('purplecow', '') 
    print(strLowerB) 
 
    # remove punctuation in strLowerB 
    punct = string.punctuation 
    for char in punct: 
      strLowerB = strLowerB.replace(char, '') 
 
    # remove spaces in strLowerB 
    strLowerB.replace(' ', '') 
    print(strLowerB) 
 
    # look for 'purplecow' in strLowerB 
    return 'purplecow' in strLowerB 
 
 
print(findPC('The purple cow is soft and cuddly. purplecow. Purple^&*(^&$cow.'))