在字符串中查找单词时结果不正确

2024-06-01 07:53:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码,可以在字符串中找到一个单词并显示它出现的次数,但是如果我输入一个字母,例如'a',它将在字符串中找到所有出现的'a',而不仅仅是'a'。我现在的代码是:

for For in SentenceSplit:
     #looks for the users word in the sentence
     if re.search(Word, str(For)):
        #if found adds one to the counter
        counter=counter+1

Tags: the字符串代码inforif字母counter
3条回答
f=open('filename','r').read()##file with the sentences
f1=f.split('\n')
l=[]
for i in range (len(f1)):
    a=f1[i].split(' ')
    for wd in a:
        l.append(wd)
c=0
word=raw_input('enter the word:')
for el in l:
    if word==l[el]:
       c+=1
if c==0:
    print 'word not found'
else:
    print 'word found, no of times=',c

希望这有帮助

可以使用split()将字符串拆分为单词,使用==进行比较。你知道吗

s = "a rat and a cat"
w = 'a'
count = 0
for useFor in s.split(' '):
    if w == useFor:
        count += 1
print count

输出:2

如果您喜欢正则表达式匹配字符串的方式,请参阅C Panda的答案。你知道吗

如果我知道你想做什么

ah a banana a fruit

应该分成

ah, a, banana, a, fruit

如果要查找a,则ahbananafruit不应匹配,而a的两个匹配项应匹配。因此,您想要的结果是2。你知道吗

如果您正在寻找一个固定字符串(例如userWord = "a"),您可以简单地找到它

counter = userSentenceSplit.count(userWord)

例如

"ah a banana a fruit".split().count("a")

2count,如您所料,统计列表中某个元素的出现次数。(在字符串中,它统计子字符串的出现次数,这可能会让您感到困惑。)

如果您的搜索模式更复杂,并且确实需要regexp,那么可以用^{}替换re.search,它只匹配搜索字符串的开头。你知道吗

如果您的搜索模式包含结束符(例如,您不希望aah匹配),请确保在$中结束模式。你知道吗

>>> re.match("a", "a")
<_sre.SRE_Match object; span=(0, 1), match='a'>
>>> re.match("a", "a longer string")
<_sre.SRE_Match object; span=(0, 1), match='a'>
>>> re.match("a$", "a")
<_sre.SRE_Match object; span=(0, 1), match='a'>
>>> re.match("a$", "a longer string") # No match
None

相关问题 更多 >