[英]Python - Find words in string
我知道我可以用
if word in my_string:
但是我想這樣查找字符串中的所有“單詞”。
counter = 0
while True:
if word in my_string:
counter += 1
我如何做而又不會一遍又一遍地“計數”相同的單詞?
如果你想確保它像計數一個完整的字is
只會有一個在this is
,即使有一個is
在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
中的is in this
匹配,則:
>>> s = 'is this is'
>>> counter = len(s.split(word))-1
>>> counter
3
換句話說,在每次出現單詞時split
字符串split
,然后減一以獲得計數。
這是漫長的一天,所以我完全忘記了,但是str
對於此str.count(substring)
具有內置方法,該方法與第二個答案相同,但可讀性更高。 請考慮使用此方法(並查看其他人的答案以了解方法)
字符串實際上已經具有您要尋找的功能。 您只需要使用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')
將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)
使用正則表達式:
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
。 您可以更改正則表達式以使其完全匹配您的單詞
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.