【问题标题】:Python: How to count dot dot dot pattern at the end of strings? [duplicate]Python:如何计算字符串末尾的点点图案? [复制]
【发布时间】:2018-02-08 23:14:35
【问题描述】:

我有这样的字符串:

Python 太棒了...

我真的要告诉你......

永不放弃..

我想用python来计算字符串末尾到底有多少个点。

功能:

string.endswith(".")

只给我 True 或 False 布尔值。有没有办法得到确切的数字?

【问题讨论】:

    标签: python regex nlp pattern-matching nltk


    【解决方案1】:

    你可以这样做

    import re
    text = '''
    Python is awesome...
    I really have to tell you ......
    never give up..
    '''
    out = re.findall('\.+$', text)
    for o in out:
        print len(o)
    

    【讨论】:

    • 请在您的答案中格式化代码,避免使用 'u' 代替 'you' 等...
    【解决方案2】:

    你可以这样做:

    def get_dots_num(line):
        count=0
        for i in range(len(line)):
            if line[(i*-1)] == '.':
                count+=1
        return count
    
    if __name__ == "__main__":
    
        line = "hello......"
        if(line.endswith('.')):
            print str(get_dots_num(line))
    

    【讨论】:

      【解决方案3】:

      如果点只在最后,它应该会有所帮助:

      string.count('.')
      

      但是如果短语不仅结尾有点 - 它需要改变

      【讨论】:

        【解决方案4】:

        你可以使用代码

        import re
        
        regex = r"\.+(?=\.*)$"
        
        test_str = ("Python is awesome...")
        
        matches = re.finditer(regex, test_str, re.MULTILINE)
        count = 0;
        
        for matchNum, match in enumerate(matches):
            matchNum = matchNum + 1
        
            print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
            count = count + match.end() - match.start();
        print count;
        

        【讨论】:

        • 你为什么使用正则表达式?
        • 问题中的 OP 标记正则表达式
        【解决方案5】:

        你可以这样做:

        counter = 0
        while True:
            if string.endswith('.'):
                counter += 1
                string = string[:-1]  # here we remove the last character
            else:
                break
        print("number of dots at the end: " + counter)
        

        【讨论】:

          猜你喜欢
          • 2018-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-03
          • 2020-01-01
          • 1970-01-01
          • 2017-05-14
          • 1970-01-01
          相关资源
          最近更新 更多