For循环:保留精确的字符串(带空格和引号)以识别单词出现(python)

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

Bit 在这里遇到了编码挑战!我正在编写一个函数,它接受两个参数(字符串、查询)并打印每个查询字符串在输入字符串中出现的次数。我想我已经很接近解决这个问题了,但是我的函数目前对带有空格的查询字符串不敏感 before/after 查询字符串。

版本 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)

当前输出:

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)

当前输出:

0
0
0

预期输出:

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)

运行 您输入的函数将提供所需的输出!这通过检查查询字符串是否匹配(没有空格 .strip())来工作。

这是我的输出:

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

输出:

2
1
0