Python/strings/detecting_english_programmatically.py

51 lines
1.4 KiB
Python
Raw Permalink Normal View History

2016-08-02 17:46:55 +00:00
import os
from string import ascii_letters
2016-08-02 17:46:55 +00:00
LETTERS_AND_SPACE = ascii_letters + " \t\n"
2019-10-05 05:14:13 +00:00
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()
matches = len([word for word in possible_words if word in ENGLISH_WORDS])
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:
return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE)
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()