【发布时间】:2018-02-08 23:14:35
【问题描述】:
我有这样的字符串:
Python 太棒了...
我真的要告诉你......
永不放弃..
我想用python来计算字符串末尾到底有多少个点。
功能:
string.endswith(".")
只给我 True 或 False 布尔值。有没有办法得到确切的数字?
【问题讨论】:
标签: python regex nlp pattern-matching nltk
我有这样的字符串:
Python 太棒了...
我真的要告诉你......
永不放弃..
我想用python来计算字符串末尾到底有多少个点。
功能:
string.endswith(".")
只给我 True 或 False 布尔值。有没有办法得到确切的数字?
【问题讨论】:
标签: python regex nlp pattern-matching nltk
你可以这样做
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)
【讨论】:
你可以这样做:
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))
【讨论】:
如果点只在最后,它应该会有所帮助:
string.count('.')
但是如果短语不仅结尾有点 - 它需要改变
【讨论】:
你可以使用代码
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;
【讨论】:
你可以这样做:
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)
【讨论】: