Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

text.py 13KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import re
  2. import unicodedata
  3. from gzip import GzipFile
  4. from gzip import compress as gzip_compress
  5. from io import BytesIO
  6. from django.core.exceptions import SuspiciousFileOperation
  7. from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy
  8. from django.utils.regex_helper import _lazy_re_compile
  9. from django.utils.translation import gettext as _
  10. from django.utils.translation import gettext_lazy, pgettext
  11. @keep_lazy_text
  12. def capfirst(x):
  13. """Capitalize the first letter of a string."""
  14. if not x:
  15. return x
  16. if not isinstance(x, str):
  17. x = str(x)
  18. return x[0].upper() + x[1:]
  19. # Set up regular expressions
  20. re_words = _lazy_re_compile(r"<[^>]+?>|([^<>\s]+)", re.S)
  21. re_chars = _lazy_re_compile(r"<[^>]+?>|(.)", re.S)
  22. re_tag = _lazy_re_compile(r"<(/)?(\S+?)(?:(\s*/)|\s.*?)?>", re.S)
  23. re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines
  24. re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))")
  25. @keep_lazy_text
  26. def wrap(text, width):
  27. """
  28. A word-wrap function that preserves existing line breaks. Expects that
  29. existing line breaks are posix newlines.
  30. Preserve all white space except added line breaks consume the space on
  31. which they break the line.
  32. Don't wrap long words, thus the output text may have lines longer than
  33. ``width``.
  34. """
  35. def _generator():
  36. for line in text.splitlines(True): # True keeps trailing linebreaks
  37. max_width = min((line.endswith("\n") and width + 1 or width), width)
  38. while len(line) > max_width:
  39. space = line[: max_width + 1].rfind(" ") + 1
  40. if space == 0:
  41. space = line.find(" ") + 1
  42. if space == 0:
  43. yield line
  44. line = ""
  45. break
  46. yield "%s\n" % line[: space - 1]
  47. line = line[space:]
  48. max_width = min((line.endswith("\n") and width + 1 or width), width)
  49. if line:
  50. yield line
  51. return "".join(_generator())
  52. class Truncator(SimpleLazyObject):
  53. """
  54. An object used to truncate text, either by characters or words.
  55. """
  56. def __init__(self, text):
  57. super().__init__(lambda: str(text))
  58. def add_truncation_text(self, text, truncate=None):
  59. if truncate is None:
  60. truncate = pgettext(
  61. "String to return when truncating text", "%(truncated_text)s…"
  62. )
  63. if "%(truncated_text)s" in truncate:
  64. return truncate % {"truncated_text": text}
  65. # The truncation text didn't contain the %(truncated_text)s string
  66. # replacement argument so just append it to the text.
  67. if text.endswith(truncate):
  68. # But don't append the truncation text if the current text already
  69. # ends in this.
  70. return text
  71. return "%s%s" % (text, truncate)
  72. def chars(self, num, truncate=None, html=False):
  73. """
  74. Return the text truncated to be no longer than the specified number
  75. of characters.
  76. `truncate` specifies what should be used to notify that the string has
  77. been truncated, defaulting to a translatable string of an ellipsis.
  78. """
  79. self._setup()
  80. length = int(num)
  81. text = unicodedata.normalize("NFC", self._wrapped)
  82. # Calculate the length to truncate to (max length - end_text length)
  83. truncate_len = length
  84. for char in self.add_truncation_text("", truncate):
  85. if not unicodedata.combining(char):
  86. truncate_len -= 1
  87. if truncate_len == 0:
  88. break
  89. if html:
  90. return self._truncate_html(length, truncate, text, truncate_len, False)
  91. return self._text_chars(length, truncate, text, truncate_len)
  92. def _text_chars(self, length, truncate, text, truncate_len):
  93. """Truncate a string after a certain number of chars."""
  94. s_len = 0
  95. end_index = None
  96. for i, char in enumerate(text):
  97. if unicodedata.combining(char):
  98. # Don't consider combining characters
  99. # as adding to the string length
  100. continue
  101. s_len += 1
  102. if end_index is None and s_len > truncate_len:
  103. end_index = i
  104. if s_len > length:
  105. # Return the truncated string
  106. return self.add_truncation_text(text[: end_index or 0], truncate)
  107. # Return the original string since no truncation was necessary
  108. return text
  109. def words(self, num, truncate=None, html=False):
  110. """
  111. Truncate a string after a certain number of words. `truncate` specifies
  112. what should be used to notify that the string has been truncated,
  113. defaulting to ellipsis.
  114. """
  115. self._setup()
  116. length = int(num)
  117. if html:
  118. return self._truncate_html(length, truncate, self._wrapped, length, True)
  119. return self._text_words(length, truncate)
  120. def _text_words(self, length, truncate):
  121. """
  122. Truncate a string after a certain number of words.
  123. Strip newlines in the string.
  124. """
  125. words = self._wrapped.split()
  126. if len(words) > length:
  127. words = words[:length]
  128. return self.add_truncation_text(" ".join(words), truncate)
  129. return " ".join(words)
  130. def _truncate_html(self, length, truncate, text, truncate_len, words):
  131. """
  132. Truncate HTML to a certain number of chars (not counting tags and
  133. comments), or, if words is True, then to a certain number of words.
  134. Close opened tags if they were correctly closed in the given HTML.
  135. Preserve newlines in the HTML.
  136. """
  137. if words and length <= 0:
  138. return ""
  139. html4_singlets = (
  140. "br",
  141. "col",
  142. "link",
  143. "base",
  144. "img",
  145. "param",
  146. "area",
  147. "hr",
  148. "input",
  149. )
  150. # Count non-HTML chars/words and keep note of open tags
  151. pos = 0
  152. end_text_pos = 0
  153. current_len = 0
  154. open_tags = []
  155. regex = re_words if words else re_chars
  156. while current_len <= length:
  157. m = regex.search(text, pos)
  158. if not m:
  159. # Checked through whole string
  160. break
  161. pos = m.end(0)
  162. if m[1]:
  163. # It's an actual non-HTML word or char
  164. current_len += 1
  165. if current_len == truncate_len:
  166. end_text_pos = pos
  167. continue
  168. # Check for tag
  169. tag = re_tag.match(m[0])
  170. if not tag or current_len >= truncate_len:
  171. # Don't worry about non tags or tags after our truncate point
  172. continue
  173. closing_tag, tagname, self_closing = tag.groups()
  174. # Element names are always case-insensitive
  175. tagname = tagname.lower()
  176. if self_closing or tagname in html4_singlets:
  177. pass
  178. elif closing_tag:
  179. # Check for match in open tags list
  180. try:
  181. i = open_tags.index(tagname)
  182. except ValueError:
  183. pass
  184. else:
  185. # SGML: An end tag closes, back to the matching start tag,
  186. # all unclosed intervening start tags with omitted end tags
  187. open_tags = open_tags[i + 1 :]
  188. else:
  189. # Add it to the start of the open tags list
  190. open_tags.insert(0, tagname)
  191. if current_len <= length:
  192. return text
  193. out = text[:end_text_pos]
  194. truncate_text = self.add_truncation_text("", truncate)
  195. if truncate_text:
  196. out += truncate_text
  197. # Close any tags still open
  198. for tag in open_tags:
  199. out += "</%s>" % tag
  200. # Return string
  201. return out
  202. @keep_lazy_text
  203. def get_valid_filename(name):
  204. """
  205. Return the given string converted to a string that can be used for a clean
  206. filename. Remove leading and trailing spaces; convert other spaces to
  207. underscores; and remove anything that is not an alphanumeric, dash,
  208. underscore, or dot.
  209. >>> get_valid_filename("john's portrait in 2004.jpg")
  210. 'johns_portrait_in_2004.jpg'
  211. """
  212. s = str(name).strip().replace(" ", "_")
  213. s = re.sub(r"(?u)[^-\w.]", "", s)
  214. if s in {"", ".", ".."}:
  215. raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
  216. return s
  217. @keep_lazy_text
  218. def get_text_list(list_, last_word=gettext_lazy("or")):
  219. """
  220. >>> get_text_list(['a', 'b', 'c', 'd'])
  221. 'a, b, c or d'
  222. >>> get_text_list(['a', 'b', 'c'], 'and')
  223. 'a, b and c'
  224. >>> get_text_list(['a', 'b'], 'and')
  225. 'a and b'
  226. >>> get_text_list(['a'])
  227. 'a'
  228. >>> get_text_list([])
  229. ''
  230. """
  231. if not list_:
  232. return ""
  233. if len(list_) == 1:
  234. return str(list_[0])
  235. return "%s %s %s" % (
  236. # Translators: This string is used as a separator between list elements
  237. _(", ").join(str(i) for i in list_[:-1]),
  238. str(last_word),
  239. str(list_[-1]),
  240. )
  241. @keep_lazy_text
  242. def normalize_newlines(text):
  243. """Normalize CRLF and CR newlines to just LF."""
  244. return re_newlines.sub("\n", str(text))
  245. @keep_lazy_text
  246. def phone2numeric(phone):
  247. """Convert a phone number with letters into its numeric equivalent."""
  248. char2number = {
  249. "a": "2",
  250. "b": "2",
  251. "c": "2",
  252. "d": "3",
  253. "e": "3",
  254. "f": "3",
  255. "g": "4",
  256. "h": "4",
  257. "i": "4",
  258. "j": "5",
  259. "k": "5",
  260. "l": "5",
  261. "m": "6",
  262. "n": "6",
  263. "o": "6",
  264. "p": "7",
  265. "q": "7",
  266. "r": "7",
  267. "s": "7",
  268. "t": "8",
  269. "u": "8",
  270. "v": "8",
  271. "w": "9",
  272. "x": "9",
  273. "y": "9",
  274. "z": "9",
  275. }
  276. return "".join(char2number.get(c, c) for c in phone.lower())
  277. def compress_string(s):
  278. return gzip_compress(s, compresslevel=6, mtime=0)
  279. class StreamingBuffer(BytesIO):
  280. def read(self):
  281. ret = self.getvalue()
  282. self.seek(0)
  283. self.truncate()
  284. return ret
  285. # Like compress_string, but for iterators of strings.
  286. def compress_sequence(sequence):
  287. buf = StreamingBuffer()
  288. with GzipFile(mode="wb", compresslevel=6, fileobj=buf, mtime=0) as zfile:
  289. # Output headers...
  290. yield buf.read()
  291. for item in sequence:
  292. zfile.write(item)
  293. data = buf.read()
  294. if data:
  295. yield data
  296. yield buf.read()
  297. # Expression to match some_token and some_token="with spaces" (and similarly
  298. # for single-quoted strings).
  299. smart_split_re = _lazy_re_compile(
  300. r"""
  301. ((?:
  302. [^\s'"]*
  303. (?:
  304. (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
  305. [^\s'"]*
  306. )+
  307. ) | \S+)
  308. """,
  309. re.VERBOSE,
  310. )
  311. def smart_split(text):
  312. r"""
  313. Generator that splits a string by spaces, leaving quoted phrases together.
  314. Supports both single and double quotes, and supports escaping quotes with
  315. backslashes. In the output, strings will keep their initial and trailing
  316. quote marks and escaped quotes will remain escaped (the results can then
  317. be further processed with unescape_string_literal()).
  318. >>> list(smart_split(r'This is "a person\'s" test.'))
  319. ['This', 'is', '"a person\\\'s"', 'test.']
  320. >>> list(smart_split(r"Another 'person\'s' test."))
  321. ['Another', "'person\\'s'", 'test.']
  322. >>> list(smart_split(r'A "\"funky\" style" test.'))
  323. ['A', '"\\"funky\\" style"', 'test.']
  324. """
  325. for bit in smart_split_re.finditer(str(text)):
  326. yield bit[0]
  327. @keep_lazy_text
  328. def unescape_string_literal(s):
  329. r"""
  330. Convert quoted string literals to unquoted strings with escaped quotes and
  331. backslashes unquoted::
  332. >>> unescape_string_literal('"abc"')
  333. 'abc'
  334. >>> unescape_string_literal("'abc'")
  335. 'abc'
  336. >>> unescape_string_literal('"a \"bc\""')
  337. 'a "bc"'
  338. >>> unescape_string_literal("'\'ab\' c'")
  339. "'ab' c"
  340. """
  341. if not s or s[0] not in "\"'" or s[-1] != s[0]:
  342. raise ValueError("Not a string literal: %r" % s)
  343. quote = s[0]
  344. return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\")
  345. @keep_lazy_text
  346. def slugify(value, allow_unicode=False):
  347. """
  348. Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
  349. dashes to single dashes. Remove characters that aren't alphanumerics,
  350. underscores, or hyphens. Convert to lowercase. Also strip leading and
  351. trailing whitespace, dashes, and underscores.
  352. """
  353. value = str(value)
  354. if allow_unicode:
  355. value = unicodedata.normalize("NFKC", value)
  356. else:
  357. value = (
  358. unicodedata.normalize("NFKD", value)
  359. .encode("ascii", "ignore")
  360. .decode("ascii")
  361. )
  362. value = re.sub(r"[^\w\s-]", "", value.lower())
  363. return re.sub(r"[-\s]+", "-", value).strip("-_")
  364. def camel_case_to_spaces(value):
  365. """
  366. Split CamelCase and convert to lowercase. Strip surrounding whitespace.
  367. """
  368. return re_camel_case.sub(r" \1", value).strip().lower()
  369. def _format_lazy(format_string, *args, **kwargs):
  370. """
  371. Apply str.format() on 'format_string' where format_string, args,
  372. and/or kwargs might be lazy.
  373. """
  374. return format_string.format(*args, **kwargs)
  375. format_lazy = lazy(_format_lazy, str)