2016-08-02 17:46:55 +00:00
|
|
|
import os
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + " \t\n"
|
|
|
|
|
2016-08-02 15:33:29 +00:00
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def load_dictionary() -> dict[str, None]:
|
2016-08-02 17:46:55 +00:00
|
|
|
path = os.path.split(os.path.realpath(__file__))
|
2022-05-13 05:55:53 +00:00
|
|
|
english_words: dict[str, None] = {}
|
|
|
|
with open(path[0] + "/dictionary.txt") as dictionary_file:
|
|
|
|
for word in dictionary_file.read().split("\n"):
|
|
|
|
english_words[word] = None
|
|
|
|
return english_words
|
2016-08-02 15:33:29 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
ENGLISH_WORDS = load_dictionary()
|
2016-08-02 15:33:29 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def get_english_count(message: str) -> float:
|
2016-08-02 15:33:29 +00:00
|
|
|
message = message.upper()
|
2022-05-13 05:55:53 +00:00
|
|
|
message = remove_non_letters(message)
|
|
|
|
possible_words = message.split()
|
2016-08-02 15:33:29 +00:00
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
if possible_words == []:
|
2016-08-02 15:33:29 +00:00
|
|
|
return 0.0
|
|
|
|
|
|
|
|
matches = 0
|
2022-05-13 05:55:53 +00:00
|
|
|
for word in possible_words:
|
2016-08-02 15:33:29 +00:00
|
|
|
if word in ENGLISH_WORDS:
|
|
|
|
matches += 1
|
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
return float(matches) / len(possible_words)
|
2016-08-02 15:33:29 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def remove_non_letters(message: str) -> str:
|
|
|
|
letters_only = []
|
2016-08-02 15:33:29 +00:00
|
|
|
for symbol in message:
|
|
|
|
if symbol in LETTERS_AND_SPACE:
|
2022-05-13 05:55:53 +00:00
|
|
|
letters_only.append(symbol)
|
|
|
|
return "".join(letters_only)
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2016-08-02 15:33:29 +00:00
|
|
|
|
2022-05-13 05:55:53 +00:00
|
|
|
def is_english(
|
|
|
|
message: str, word_percentage: int = 20, letter_percentage: int = 85
|
|
|
|
) -> bool:
|
2016-08-02 17:46:55 +00:00
|
|
|
"""
|
2022-05-13 05:55:53 +00:00
|
|
|
>>> is_english('Hello World')
|
2016-08-02 17:46:55 +00:00
|
|
|
True
|
2022-05-13 05:55:53 +00:00
|
|
|
>>> is_english('llold HorWd')
|
2016-08-02 17:46:55 +00:00
|
|
|
False
|
|
|
|
"""
|
2022-05-13 05:55:53 +00:00
|
|
|
words_match = get_english_count(message) * 100 >= word_percentage
|
|
|
|
num_letters = len(remove_non_letters(message))
|
|
|
|
message_letters_percentage = (float(num_letters) / len(message)) * 100
|
|
|
|
letters_match = message_letters_percentage >= letter_percentage
|
|
|
|
return words_match and letters_match
|
2016-08-02 17:46:55 +00:00
|
|
|
|
|
|
|
|
2020-05-22 06:10:11 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2020-05-22 06:10:11 +00:00
|
|
|
doctest.testmod()
|