Python/strings/detecting_english_programmatically.py

63 lines
1.6 KiB
Python
Raw Normal View History

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
def load_dictionary() -> dict[str, None]:
2016-08-02 17:46:55 +00:00
path = os.path.split(os.path.realpath(__file__))
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
ENGLISH_WORDS = load_dictionary()
2016-08-02 15:33:29 +00:00
2019-10-05 05:14:13 +00:00
def get_english_count(message: str) -> float:
2016-08-02 15:33:29 +00:00
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
2016-08-02 15:33:29 +00:00
if possible_words == []:
2016-08-02 15:33:29 +00:00
return 0.0
matches = 0
for word in possible_words:
2016-08-02 15:33:29 +00:00
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possible_words)
2016-08-02 15:33:29 +00:00
2019-10-05 05:14:13 +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:
letters_only.append(symbol)
return "".join(letters_only)
2019-10-05 05:14:13 +00:00
2016-08-02 15:33:29 +00:00
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
2016-08-02 17:46:55 +00:00
"""
>>> is_english('Hello World')
2016-08-02 17:46:55 +00:00
True
>>> is_english('llold HorWd')
2016-08-02 17:46:55 +00:00
False
"""
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
if __name__ == "__main__":
import doctest
2019-10-05 05:14:13 +00:00
doctest.testmod()