Найти слова одинаковой длины [python 3 -enchant lib] - PullRequest
0 голосов
/ 06 декабря 2018

выделенный текст. Я создаю программу автозамены, которая находит слова с ошибками в куске текста и затем выдает предложения.До сих пор в коде можно было найти слова с ошибками, но он может давать советы.Одна из стратегий, которую я подумал использовать, - это найти слова одинаковой длины (с одинаковым количеством букв, но с +1 или -1 буквой), тогда он может предложить это.Примером этого может быть то, что если пользователь введет «лев спит», что означает «лев спит», программа будет искать слова с той же длиной, находя «то», а затем предлагая его.это было бы очень легко, если бы я использовал список слов, но я использую библиотеку enchant, поскольку в ней есть все английские слова, но я не могу найти способ использовать библиотеку для поиска слов одинаковой длины.Кроме того, я знаю, что он имеет встроенную функцию автозамены, но мне не разрешено использовать это.Спасибо, ребята заранее.Также я попытался отформатировать мой вопрос, насколько это возможно, и извините, если код не задокументирован, так как я работаю над этим.

wrong_words = []
while True:
  import enchant
  there_is_a_mistake = False
  punctuation = set("!#$%&()*+,./:;<=>?@[\]^_`{|}~"+'”' + '"' + '“')
  dictionary = enchant.Dict("en_US")
  keyboard_input = input()
  words_without_special_characters = "".join(x for x in keyboard_input if x not in punctuation) # https://www.youtube.com/watch?v=llf_pTNhYa4
  words_without_special_characters = words_without_special_characters.replace("-" and "—" and "-" and "–" and "-"," ")
  words_without_spaces_and_special_characters = words_without_special_characters.split()
  number_of_words = len(words_without_spaces_and_special_characters)
  for x in range(0,number_of_words):
    checked_words = dictionary.check(words_without_spaces_and_special_characters[x])
    while checked_words == False:
      read = open("saved_words.txt","r")#opens the file in reading mode.
      read_file = read.readlines()#reads from the file.
      read_file = [item.replace("\n","") for item in read_file]
      if words_without_spaces_and_special_characters[x] in read_file: # checks if the word is savedd in the clint word list
        break
      read.close()#closes the file reading for another operation.
      print(words_without_spaces_and_special_characters[x])
      words_without_spaces_and_special_characters[x].append(wrong_words)
      print("false")
      there_is_a_mistake = True
      break
  if there_is_a_mistake == True:
    keyboard_input_yes_or_no_to_save_words = input("if you want to save a word to your dictionary type :yes. (press enter if you dont want to)")
    if keyboard_input_yes_or_no_to_save_words == "yes":
      while True:
        keyboard_input_to_save_words = input("which words do you want to save? (type ignore if you dont want to)")
        keyboard_input_to_save_words = keyboard_input_to_save_words.split()
        check_if_word_was_orginally_written = set(keyboard_input_to_save_words) <= set(words_without_spaces_and_special_characters)
        if check_if_word_was_orginally_written == True:
          file = open("saved_words.txt","a+") #opens the file in the writing mode.
          for i in range(0,len(keyboard_input_to_save_words.split())):
            file.write(keyboard_input_to_save_words[i]) # writes information in the other file.
            file.write("\n") # creates new line.
          file.close()
          break
        if keyboard_input_to_save_words == "ignore":
          print("nope")
          break
        else:
          print("no words found. Try again. (type ignpre if you dont want to save any word)")
for i in range (len(wrong_words)):
  length_of_wrong_word = len(wrong_words)

1 Ответ

0 голосов
/ 06 декабря 2018

Я мало представляю, что делает enchant lib, но я бы сделал это в python3 +

Допустим, у вас есть строка в переменной с именем word

word = "hello"

Youможно проверить длину этого слова, используя len (str): len (word)

print(len(word))
>>>5

Затем вы можете использовать цикл for для проверки каждого слова в списке с длиной, соответствующей длине вашего слова.Допустим, у вас есть группа слов в списке под названием listofwords

for item in listofwords:
   if len(item) == len(word):
       print(item)

в этом цикле for, он проверяет, имеет ли какой-либо элемент в списке listofwords ту же длину, что и строковое слово (5), еслион печатает обратно указанный элемент.

...