forked from aichaos/rivescript-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
95 lines (75 loc) · 2.6 KB
/
Copy pathutils.py
File metadata and controls
95 lines (75 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# RiveScript-Python
#
# This code is released under the MIT License.
# See the "LICENSE" file for more information.
#
# https://www.rivescript.com/
from __future__ import unicode_literals
from .regexp import RE
import random
import re
import string
def word_count(trigger, all=False):
"""Count the words that aren't wildcards or options in a trigger.
:param str trigger: The trigger to count words for.
:param bool all: Count purely based on whitespace separators, or
consider wildcards not to be their own words.
:return int: The word count."""
words = []
if all:
words = re.split(RE.ws, trigger)
else:
words = re.split(RE.wilds_and_optionals, trigger)
wc = 0 # Word count
for word in words:
if len(word) > 0:
wc += 1
return wc
def is_atomic(trigger):
"""Determine if a trigger is atomic or not.
In this context we're deciding whether or not the trigger needs to use
the regular expression engine for testing. So any trigger that contains
nothing but plain words is considered atomic, whereas a trigger with any
"regexp-like" parts (even alternations) is not.
:param trigger: The trigger to test.
:return bool: Whether it's atomic or not.
"""
# Atomic triggers don't contain any wildcards or parenthesis or anything
# of the sort. We don't need to test the full character set, just left
# brackets will do.
special = ['*', '#', '_', '(', '[', '<', '{', '@']
for char in special:
if char in trigger:
return False
return True
def strip_nasties(s):
"""Formats a string for ASCII regex matching."""
s = re.sub(RE.nasties, '', s)
return s
def string_format(msg, method):
"""Format a string (upper, lower, formal, sentence).
:param str msg: The user's message.
:param str method: One of ``uppercase``, ``lowercase``,
``sentence`` or ``formal``.
:return str: The reformatted string.
"""
if method == "uppercase":
return msg.upper()
elif method == "lowercase":
return msg.lower()
elif method == "sentence":
return msg.capitalize()
elif method == "formal":
return string.capwords(msg)
def random_choice(bucket):
"""Safely get a random choice from a list.
If the list is zero-length, this just returns an empty string rather than
raise an exception.
Parameters:
bucket (list): A list to randomly choose from.
Returns:
str: The random choice. Blank string if the list was empty.
"""
if len(bucket) == 0:
return ""
return random.choice(bucket)