Python - 在字符串中查找单词

时间:2015-12-17 00:09:52

标签: python string

我知道我可以在

字符串中找到一个单词
if word in my_string:

但我想找到所有"字"在字符串中,像这样。

counter = 0
while True:
    if word in my_string:
        counter += 1

如果没有"计算"我该怎么办?同一个词一遍又一遍?

4 个答案:

答案 0 :(得分:3)

如果你想确保它算上<compatible-screens> <!-- all small size screens --> <screen android:screenSize="small" android:screenDensity="ldpi" /> <screen android:screenSize="small" android:screenDensity="mdpi" /> <screen android:screenSize="small" android:screenDensity="hdpi" /> <screen android:screenSize="small" android:screenDensity="xhdpi" /> <!-- all normal size screens --> <screen android:screenSize="normal" android:screenDensity="ldpi" /> <screen android:screenSize="normal" android:screenDensity="mdpi" /> <screen android:screenSize="normal" android:screenDensity="hdpi" /> <screen android:screenSize="normal" android:screenDensity="xhdpi" /> <screen android:screenSize="normal" android:screenDensity="420" /> <screen android:screenSize="normal" android:screenDensity="480" /> <screen android:screenSize="normal" android:screenDensity="560" /> </compatible-screens> 之类的完整字词,即使is中有this isis也只有一个字,你可以拆分,过滤和计数:

this

但是,如果您只想计算所有出现的子字符串,即>>> s = 'this is a sentences that has is and is and is (4)' >>> word = 'is' >>> counter = len([x for x in s.split() if x == word]) >>> counter 4 也会匹配is,那么:

is in this

换句话说,>>> s = 'is this is' >>> counter = len(s.split(word))-1 >>> counter 3 每次出现该字符串时的字符串,然后减去1以获得计数。

编辑 - 只能使用COUNT:

这是漫长的一天,所以我完全忘了,但split有一个内置的方法str与我的第二个答案相同,但更具可读性。请考虑使用此方法(并查看其他人的答案)

答案 1 :(得分:2)

String实际上已经具有您正在寻找的功能。您只需使用str.count(item)作为示例。

编辑:这将搜索所有出现的所述字符串,包括部分单词。

string_to_search = 'apple apple orange banana grapefruit apple banana'

number_of_apples = string_to_search.count('apple')
number_of_bananas = string_to_search.count('banana')

以下内容仅搜索完整的单词,只需分割您要搜索的字符串。

string_to_search = 'apple apple orange banana grapefruit apple banana'.split()

number_of_apples = string_to_search.count('apple')
number_of_bananas = string_to_search.count('banana')

答案 2 :(得分:1)

beg方法使用.find参数。

counter = 0
search_pos = 0
while True:
    found = my_string.find(word, search_pos)
    if found != -1: # find returns -1 when it's not found
        #update counter and move search_pos to look for the next word
        search_pos = found + len(word)
        counter += 1
    else:
        #the word wasn't found
        break

这是一种通用的解决方案。特别是对于字符串计数,您只需使用my_string.count(word)

答案 3 :(得分:0)

使用正则表达式:

import re

word = 'test'
my_string = 'this is a test and more test and a test'

# Use escape in case your search word contains periods or symbols that are used in regular expressions.
re_word = re.escape(word)

# re.findall returns a list of matches
matches = re.findall(re_word, my_string)

# matches = ['test', 'test', 'test']
print len(matches) # 3

请注意,这会包含其他包含testing字词的单词。您可以将正则表达式更改为恰好与您的单词匹配

相关问题