[英]Count occurrences of array in string
我是編程的新手,已經盡我所能進行研究/閱讀,但是還沒有找到具體的答案來幫助我。
我的問題如下,如果我有一個包含多個單詞的數組,如下所示:myArray =“ this”,“ makes”,“ bats”,“ look”,“ funny”
而且我有一串亂七八糟的單詞(包括數組中列出的單詞的一些實例,例如:string =“ jkmakespohbatsllfunnythisqwemakes”
字符串包含單詞“ makes”的兩個實例,一個“ bats”的實例,一個“ funny”的實例,一個“ this”的實例和零個“ look”的實例。
有人可以用一些偽代碼幫助我指出正確的方向,該偽代碼說明我如何在字符串中搜索數組中的任何子字符串單詞,並打印找到的每個實例(如上所述)或未找到的實例的計數。
我現在在編程語言上有所不同,但是當我對結構有了更好的了解時,可能會希望以后再編寫代碼。
謝謝!
# define a list of your words (call it 'words')
# define the string you want to search through (call it 'jumble')
# Define an empty dictionary that will hold your results. You can use a regular
# dictionary, or a cool thing in Python called "DefaultDict", in the collections module.
# Call it 'count'.
# Now loop through each of your words
# Start searching at the beginning of your jumble, by
# specifying a start position of 0. (This will make sense later.)
# Add another loop here, that keeps looping until we're sure there's no
# more words to be found.
# Try to find (hint: check out the 'string' module) the word inside of jumble.
# If we did NOT find a word
# We just 'break' out of the inner loop
# Else If we DID find a word, let's save the position of that word.
# Call that 'index'.
# If this is the first time, we put the word in our dictionary
# with a count of 1
# Else If this is not the first time, add 1 to the dictionary entry
# for that word.
# Now we search AGAIN through the jumble, but start AFTER the
# position where we saw the first time.
# Now we've exited the entire thing, let's just print out our 'count' dictionary.
那是偽代碼。
這是您可能要使用的各種功能的一些示例:
colors = ['red', 'blue', 'green'] # Lists
for color in colors: # For loops
print(color)
person = {} # Empty dictionary
person['name'] = 'Symmitchry' # Add a key / value pair to a dictionary
if 'name' in person: # Looking for a key in a dictionary
print('Person has a name:') # How to print
print(person['name']) # How to access a value from a dictionary
else: # how to write an else statement
print('Person has no name! Weird.')
import random # importing a module
x = random.randint() # Using a function from a module
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.