gpt4 book ai didi

python - 在字符串中查找短语

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:26 24 4
gpt4 key购买 nike

我正在尝试检查字符串中是否存在短语“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.'))

关于python - 在字符串中查找短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54114811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com