我试图解决这个问题,因为他们给了我一组字符串,用来计算某个单词在字符串中出现的次数,比如'code‘,但是程序也会计算任何'd’变成'coze‘的变体,但是像'coz’这样的东西不算,这是我做的:
def count(word):
count=0
for i in range(len(word)):
lo=word[i:i+4]
if lo=='co': # this is what gives me trouble
count+=1
return count发布于 2019-03-14 08:15:13
测试前两个字符是否与co匹配,第四个字符是否与e匹配。
def count(word):
count=0
for i in range(len(word)-3):
if word[i:i+1] == 'co' and word[i+3] == 'e'
count+=1
return count循环只会上升到len(word)-3,这样word[i+3]就不会超出范围。
发布于 2019-03-14 08:16:46
为此,您可以通过re模块使用正则表达式。
import re
string = 'this is a string containing the words code, coze, and coz'
re.findall(r'co.e', string)
['code', 'coze']在那里,您可以编写一个函数,如下所示:
def count(string, word):
return len(re.findall(word, string))发布于 2019-03-14 10:53:51
正则表达式是上面提到的问题的答案,但您需要的是一个更精致的正则表达式模式。由于您正在查找的是某个出现在上的词,因此您需要搜索边界词。所以你的模式应该是。如下所示:
pattern = r'\bco.e\b'这样,您的搜索将不会与诸如testcodetest或cozetest之类的单词匹配,而只与code coze coke匹配,而不与前导字符或后续字符匹配
如果你要进行多次测试,那么最好使用编译模式,这样内存效率会更高。
In [1]: import re
In [2]: string = 'this is a string containing the codeorg testcozetest words code, coze, and coz'
In [3]: pattern = re.compile(r'\bco.e\b')
In [4]: pattern.findall(string)
Out[4]: ['code', 'coze']希望这能有所帮助。
https://stackoverflow.com/questions/55152990
复制相似问题