如何按特定顺序搜索字符串中的项目

时间:2018-07-26 13:32:39

标签: python

我正在处理一些问题,最近我陷入了一个问题。我有一个像'hoouseeqwehouusseee'这样的字符串。我必须计算第一个单词'house'和另一个单词'house'之间有多少个字符。对于上面的示例,多余的字母为:'e''q''w''e',因此答案为4。我试图将字符串转换为列表,但是从这里开始,我不知道如何继续。

word = list(word)
x = []
for item in word:
    if item not in x:
        x.append(item)
print(x)

4 个答案:

答案 0 :(得分:1)

由于您的要求不明确,这可能无法解决您的确切问题,但应该为您提供一个起点。这将返回匹配h+o+u+s+e正则表达式的字符串的第一和第二个实例之间的字母数。

import re

s = 'hoouseeqwehouusseee'

def length_of_first_gap(test_string, word):
    pattern = '+'.join(list(word))
    return len(re.split(pattern, test_string)[1])

>>> length_of_first_gap(s, 'house')
>>> 4

答案 1 :(得分:1)

我想出了一个解决方案,希望它能真正解决您在问题中的真正意图。

代码:-

word = 'hoouseeqwehouusseee'
def count_char(string):
    new_string1 = word.replace('hoouse','')
    new_string2 = new_string1.replace('houusseee','')
    return len(new_string2)

print(count_char(word))

希望它对您有帮助。

答案 2 :(得分:0)

最简单的方法是使用正则表达式。

  1. 首先,我们在字符串中找到所有匹配项。
  2. 然后我们计算一个比赛结束与下一场比赛开始之间的差额。

这是一个代码:

import re
string = 'hoouseeqwehouusseee'
word = 'house'

pattern = '+'.join(word)
list_of_word_indices = [(match.start(0), match.end(0)) for match in re.finditer(pattern, string)]
list_of_gap_lengthes = [list_of_word_indices[i+1][0] - list_of_word_indices[i][1]
                        for i in range(len(list_of_word_indices)-1)] 

print(list_of_gap_lengthes)

您将获得差距列表。在您的示例中为'[4]'

希望有帮助。

答案 3 :(得分:-3)

收藏集。Counter将为您提供帮助:https://docs.python.org/2/library/collections.html#collections.Counter

class MainViewController: UIViewController {

    @IBOutlet weak var chartView: ChartView!

    lazy var tapGestureRecognizer = { UITapGestureRecognizer(target: self, action: #selector(handleGesture)) }()
    lazy var panGestureRecognizer = { UIPanGestureRecognizer(target: self, action: #selector(handleGesture)) }()
    lazy var pinchGestureRecognizer = { UIPinchGestureRecognizer(target: self, action: #selector(handleGesture)) }()

    @objc func handleGesture(_ sender: GestureRecognizer) {
        print(sender.location(in: self.view), sender.state.rawValue)

        chartView.gestureRecognizer = sender.self
        chartView.setNeedsDisplay(view.bounds)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        chartView.addGestureRecognizer(tapGestureRecognizer)
        chartView.addGestureRecognizer(panGestureRecognizer)
        chartView.addGestureRecognizer(pinchGestureRecognizer)
    }

    class ChartView: UIView {

        var gestureRecognizer: GestureRecognizer!

        override func draw(_ rect: CGRect) {

            if gestureRecognizer != nil {
                print(gestureRecognizer.location(in: self), gestureRecognizer.state.rawValue)
            }

        }
}