簡體   English   中英

Python-查找字符串中的單詞

[英]Python - Find words in string

我知道我可以用

if word in my_string:

但是我想這樣查找字符串中的所有“單詞”。

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

我如何做而又不會一遍又一遍地“計數”相同的單詞?

如果你想確保它像計數一個完整的字is只會有一個在this is ,即使有一個isthis ,你可以分割,過濾和計數:

>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM