簡體   English   中英

For循環:保留精確的字符串(帶空格和引號)以識別單詞出現(python)

[英]For loop: retaining exact strings (with spaces and quotations) to identify word occurence (python)

在這里遇到編碼挑戰,我正在編寫一個 function ,它需要兩個 arguments (字符串。查詢)並打印每個查詢字符串在輸入字符串中出現的次數。 我想我已經很接近解決這個問題了,但是我的 function 目前對查詢字符串之前/之后帶有空格的查詢字符串不敏感。

版本 1(對包含空格的查詢字符串不敏感):

strings = ['ab', ' ab', 'abc']
queries = ['ab', ' abc', ' bc']

def matchingStrings(strings, queries):
    for i in range(len(queries)):]
        n_matches = strings.count(queries[i])
        print(n_matches)

matchingStrings(strings,queries)

當前 Output:

1
0
0

版本 2(嘗試保留引號):

def matchingStrings(strings, queries):
    for i in range(len(queries)):
        query_to_match = '\'%s\'' % queries[i]
        n_matches = strings.count(query_to_match)
        print(n_matches)


matchingStrings(strings,queries)

當前 Output:

0
0
0

預期 Output:

2
1
0

這將通過使用正則表達式來工作,盡管它遍歷兩個列表時速度較慢:

def matching_strings(strings, queries):
    for query in queries:
        count = 0
        for string in strings:
            if re.match(query.strip(), string):
                count += 1
        print(count)

在您的輸入上運行 function 將提供所需的輸出! 這通過檢查查詢字符串是否匹配(不帶空格.strip() )來工作。

這是我的 output:

>>> strings = ['ab', ' ab', 'abc']
>>> queries = ['ab', ' abc', ' bc']
>>> matching_strings(strings, queries)
2
1
0

所以這個解決方案接近正確的答案,但有一些事情正在發生。 首先,要將所有查詢與所有字符串進行比較,我們需要兩個 for 循環。 這是幫助可視化正在發生的事情的偽代碼:

  1. 對於查詢中的每個查詢:開始計數以計算字符串中有多少單詞與當前查詢匹配。 將為每個查詢重置。
  2. 對於我們想要與當前查詢比較的每個單詞:我們不關心空格,因此我們將從查詢和字符串中刪除它。
  3. 如果剝離后單詞和查詢相同:
  4. 在櫃台上加一個。
  5. 在檢查完所有單詞后,打印計數,其中包含與當前查詢匹配的單詞數。
  6. 繼續下一個查詢。

如果您想看的話,這里是 python。

strings = ['ab', ' ab', 'abc']
queries = ['ab', ' abc', ' bc']

def matchingStrings(strings, queries):
    for query in queries:
        count = 0 
        # need to iterate through ALL strings. 
        for string in strings:
            if query.strip() == string.strip():
               count += 1
        print(count)

matchingStrings(strings, queries)

使用 output:

2
1
0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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