Как исправить Python не писать в файл - PullRequest
0 голосов
/ 11 июля 2019

Я делаю скрипт, который читает словарь и выбирает слова, которые соответствуют критериям поиска.Код работает нормально, но проблема в том, что он не записывает слова в файл «вау» и не распечатывает их.Источник для словаря: https://github.com/dwyl/english-words/blob/master/words.zip.

Я пытался изменить открытие файла на «w +» вместо «a +», но это не имело значения.Я проверил, не было ли просто слов, которые соответствовали бы критериям, но это не проблема.

listExample = []  #creates a list

with open("words.txt") as f:  #opens the "words" text file
    for line in f:
        listExample.append(line)

x = 0
file = open("wow.txt","a+") #opens "wow" so I can save the right words to it

while True:
    if x < 5000: # limits the search because I don't want to wait too long
        if len(listExample[x]) == 11: #this loop iterates through all words
            word = listExample[x]     #if the words is 11 letters long  
            lastLetter = word[10]
            print(x)
            if lastLetter == "t":    #and the last letter is t
                file.write(word)      #it writes the word to the file "wow"
                print("This word is cool!",word) #and prints it
            else:
                print(word) #or it just prints it
        x += 1 #iteration
    else:
        file.close()
        break #breaks after 5000 to keep it short

Он создал файл "вау", но он пуст.Как я могу исправить эту проблему?

1 Ответ

2 голосов
/ 11 июля 2019

Это исправит вашу проблему.Вы разбивали текст таким образом, чтобы каждое слово имело разрыв строки в конце и, возможно, также пробел.Я вставил .strip(), чтобы избавиться от любых пробелов.Также я определил lastLetter как word[-1], чтобы получить окончательную букву независимо от длины слова.

PS Спасибо Ocaso Protal за предложение полосы вместо замены.

listExample = []  #creates a list

with open("words.txt") as f:  #opens the "words" text file
    for line in f:
        listExample.append(line)

x = 0
file = open("wow.txt","a+") #opens "wow" so I can save the right words to it

while True:
    if x < 5000: # limits the search because I don't want to wait too long
        word = listExample[x].strip()
        if len(word) == 11:
            lastLetter = word[-1]
            print(x)
            if lastLetter == "t":    #and the last letter is t
                file.write(word + '\n')      #it writes the word to the file "wow"
                print("This word is cool!",word) #and prints it
            else:
                print(word) #or it just prints it
        x += 1 #iteration
    else:
        print('closing')
        file.close()
        break #breaks after 5000 to keep it short
...