2016-11-25 3 views
1

Мне нужна помощь с моим кодом на Python. Я пытался сохранить предложение, введенное в текстовый файл, без повторения слов в файле. Я не знаю, как это сделать.Код Python - не знаю о текстовых файлах

Любая помощь приветствуется.

Это мой код:

import sys 

#user-friendly, informs the user what do to 
answer = input("What is your name?\n") 
print("Hello " + answer + " and welcome to this program!\n") 
print("This program will ask you for a sentence and print out the positions of the words instead of the actual words. it will then save it in a file with the sentence.\n") 

repeat = True 
loop = True 
true = True 

#Allows the user to decide whether or not they want to use the program 
while repeat: 
    answer2 = input("Do you want to do run this program?\n") 
    #if the answer is 'no' then the program stops 
    if answer2.lower() == "No" or answer2.lower() == "nah" or answer2.lower() == "no" or answer2.lower() == "n": 
     print ("Okay then ... Bye.") 
     sys.exit() 
    #if the answer is 'yes' then the code continues 
    elif answer2 == "Yes".lower() or answer2.lower() == "yeah" or answer2.lower() == "yes" or answer2.lower() == "y": 
     print ("Okay then ... \n") 
     while true: 
      if loop == True: 
       sentence = input("Please enter a sentence:\n").lower() 
      #converts the sentence into a list 
      s = sentence.split() 
      #works out the positions of the words 
      positions = [s.index(x)+1 for x in s] 
      print(positions) 

      #opens a text file 
      fi = open("CA Task 2.txt", "w") 
      #Allows you to write over the original content in the file 
      fi.write(str(s)) 
      #it closes the file once you've finished with it 
      fi.close() 

      #opens a text file 
      fi = open("CA Task 2.txt", "a") 
      #Allows you to add to the text file instead of writing over it 
      fi.write("\n") 
      fi.write(str(positions)) 
      #it closes the file once you've finished with it 
      fi.close() 
      sys.exit() 

    #if the answer is neither 'yes' nor 'no' then the programs jumps to this part and allows the user to try again 
    else: 
     print("Please enter a valid answer! Try again!\n") 

Давайте просто скажем, предложение, введенный в «Не спрашивай, что твоя страна может сделать для вас, но то, что вы можете сделать для своей страны».

Он должен прийти, говоря: спросить, что ваша страна может сделать для вас, но то, что вы можете сделать для своей страны

[1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 3, 9, 6, 7, 8, 4, 5]

Это работает, а затем его необходимо сохранить в текстовый файл: ['ask', 'not', 'what', ' ваши ',' country ',' can ',' do ',' for ',' you ',' but ',' what ',' you ',' can ',' do ',' for ',' your ' , 'страна']

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 9, 6, 7, 8, 4, 5]

Это прекрасно, но я хочу, чтобы это не повторять слово, если оно уже упоминалось один раз в текстовом файле.

+0

Не совсем уверен, что вы просите о помощи с здесь. Что вы ожидаете - может быть, пример ввода пользователем и то, что было бы сохранено в файле, было бы удобно. И что в настоящее время происходит. – freebie

+0

В основном я хочу, чтобы пользователь вводил предложение (это работает), а затем я хочу сохранить его в текстовом файле с позициями (это также работает). Но что я не знаю, что делать, если слово в предложении повторяется, как вы храните это из текстового файла @freebie –

+0

@AsifKhan, можете ли вы добавить свой ожидаемый ответ в свой вопрос? это может быть изображение или текст, который поможет понять ваш вопрос. –

ответ

3

Там построена как функция называется: sethttps://docs.python.org/3/library/stdtypes.html#set:

import sys 

#user-friendly, informs the user what do to 
answer = input("What is your name?\n") 
print("Hello " + answer + " and welcome to this program!\n") 
print("This program will ask you for a sentence and print out the positions of the words instead of the actual words. it will then save it in a file with the sentence.\n") 

repeat = True 
loop = True 
true = True 

#Allows the user to decide whether or not they want to use the program 
while repeat: 
    answer2 = input("Do you want to do run this program?\n") 
    #if the answer is 'no' then the program stops 
    if answer2.lower() == "No" or answer2.lower() == "nah" or answer2.lower() == "no" or answer2.lower() == "n": 
    print ("Okay then ... Bye.") 
    sys.exit() 
#if the answer is 'yes' then the code continues 
elif answer2 == "Yes".lower() or answer2.lower() == "yeah" or answer2.lower() == "yes" or answer2.lower() == "y": 
    print ("Okay then ... \n") 
    while true: 
     if loop == True: 
      sentence = input("Please enter a sentence:\n").lower() 
     # converts the sentence into a list 
     s = sentence.split() 
     # for loop makes sure that if the word is in the list then it wont print it out again 
     for word in s: 
      if word not in s: 
       s.append(word) 
     # works out the positions of the words 
     positions = [s.index(x) + 1 for x in s] 
     print(set(positions)) 

     # opens a text file 
     fi = open("CA Task 2.txt", "w") 
     # Allows you to write over the original content in the file 
     fi.write(str(set(s))) 
     # it closes the file once you've finished with it 
     fi.close() 

     # opens a text file 
     fi = open("CA Task 2.txt", "a") 
     # Allows you to add to the text file instead of writing over it 
     fi.write("\n") 
     fi.write(str(set(positions))) 
     # it closes the file once you've finished with it 
     fi.close() 
     sys.exit() 

     #if the answer is neither 'yes' nor 'no' then the programs jumps to this part and allows the user to try again 
     else: 
     print("Please enter a valid answer! Try again!\n")' 
0

Это:

for word in s: 
    if word not in s: 
     s.append(word) 

не имеет смысла для меня. Вы пытаетесь создать список уникальных слов? Он дает вам тот же список.

Также if answer2.lower() == "No" является превосходным, поскольку в результате никогда не будет «Нет».

Допустим, у вас есть список из предложения, в котором некоторые слова являются уникальными, а некоторые из них не: s = ['foo', 'bar', 'foo', 'foo', 'spam'] , и вы хотите, чтобы получить цифровое представление этих уникальных слов, вы можете получить его так:

d = [] 
i = 0 
for item in s: 
    if item not in s[:i]: 
     d.append(i) 
     i += 1 
    else: 
     d.append(s.index(item)) 

Теперь вы получите список, где каждая цифра представляет собой уникальное представление слов с:

[0, 1, 0, 0, 2] 
2

Так что это ваше для секции петли, которая не ведет себя? Мне кажется, что вы раскалываете предложение в список так ['here', 'is', 'my', 'sentence', 'input'], а затем перебираете каждое из этих слов и добавляете их обратно в список, если они еще не находятся в нем. Поэтому это должно никогда не сказаться на s.

Python имеет коллекцию set, которая содержит уникальные значения. Так что это как list, но не позволяет добавлять дубликаты. Вы можете использовать это вместо цикла for, поскольку вы можете инициализировать set с помощью list - как и одно использование, созданное из вашего вызова split().

s = sentence.split() 
s = set(s) 

Редактировать: наборы не сохраняют порядок, как list. Поэтому, если сохранение слов в порядке первого появления важно, этот метод не будет работать.

0

Измените деталь, в которой вы проверяете, находится ли слово в s. Вы должны сохранить свои слова в другом списке и проверить, находится ли слово s в другом списке. Как и в приведенном ниже коде:

#for loop makes sure that if the word is in the list then it wont print it out again 
    new_s = [] 
    for word in s: 
     if word not in new_s: 
      new_s.append(word) 
+0

Я пробовал это, но он, похоже, не работает –

Смежные вопросы