如何在python中查找特定单词之间的空白

如何在python中查找特定单词之间的空白,python,Python,我试图找到特定单词与其相邻单词之间的空格计数 我有以下字符串: "${test}= Test word browser mozilla" 现在,我正在尝试计算word测试单词和浏览器之间的空格数。这个词是每行的变化 注意-这两个单词之间有多个空格。可能是这样吗 >>> import re >>> string = "${test}= Test word browser mozilla" >>&g

我试图找到特定单词与其相邻单词之间的空格计数

我有以下字符串:

"${test}=    Test word      browser      mozilla"
现在,我正在尝试计算word
测试单词
浏览器
之间的空格数。这个词是每行的变化

注意-这两个单词之间有多个空格。

可能是这样吗

>>> import re
>>> string = "${test}=    Test word      browser      mozilla"
>>> re.search('Test word( +)browser', string).group(1)
'      '
>>> len(re.search('Test word( +)browser', string).group(1))
6
>>> 
或不带正则表达式:

>>> string = "${test}=    Test word      browser      mozilla"
>>> string.split('Test word')[1].split('browser')[0]
'      '
>>> len(string.split('Test word')[1].split('browser')[0])
6
>>> 

使用正则表达式:

import re

s = '${test}= Test word browser mozilla'
target = 'Test word'
pattern = r'{}(\s+)'.format(target)
count = len(re.findall(pattern, s)[0])
此正则表达式模式将在字符串中定位目标字,并匹配其后的任何空格字符序列

另一种方法是使用拆分目标单词上的字符串,然后处理该字符串的结果:

import string

s = '${test}= Test word browser mozilla'
target = 'Test word'
head, sep, tail = s.partition(target)
if tail:
    count = 0
    for c in tail:
        if c in string.whitespace:
            count += 1
        else:
            break
    print(count)
else:
    print("Target word(s) {} not present".format(target))

我的建议是看一看正则表达式。这需要知道相邻的单词。我不确定它是不是。@mhawke:Hmm…OP说现在我正试图计算单词
测试单词
浏览器
之间的空格数@mhawke:事实上,如果我们不知道相邻的单词是什么,可以通过RegEx:
len(re.search('Test word(+)\w',string.group(1))
或使用
str split()
首先获取相邻单词。是的,我的答案中已经有一个不需要知道以下单词的正则表达式解决方案。它还处理空格以外的空格字符,例如制表符、换行符等。