2017-03-02 6 views
-1

私は、文章中の個々の単語を識別し、それらをリストに格納し、元の文中の各単語をリスト内のその単語の位置に置き換えるプログラムを開発する課題を与えられています。私は、コードを行っているが、私はそれを実行すると、私はエラーを取得する:ここでテキスト圧縮時のValueError

Traceback (most recent call last): 
    File line 11, in <module> 
    PositionOfWords = list2.index(word) 
ValueError: Substring not found 

は私のコードです:

UserSentence = input("enter sentence:").lower() 
words = UserSentence.split() 
PositionOfWords = [words] 
list1 = [] 
list2 = "" 

for word in words: 
    if PositionOfWords not in list1: 
     list1.append(PositionOfWords) 
    for word in words: 
     PositionOfWords = list2.index(word) 
     list2+=string(PositionOfWords+int("1")) 
     list2 +=("") 
    list1str += ";".join(list) 
file = open ("filename.txt","w") 
file.write 
file.write(sentence) 
file.write(list1str) 
file.write(list2) 
file = open ("filename.txt", "r") 
print (file.read()) 
file.close 
+0

エラー明らかです。 'list2'は空ですので、あなたはどんな単語のインデックスも取得できません。あなたは本当にあなた自身でこれを書いていましたか? – linusg

+0

ええ、私は事をやったのですが、とにかく良いプログラマではありません。 –

+0

'.index'は、リスト(または文字列ですが、ターゲットがリストであるかのように使用しようとしています)の要素のインデックスを取得します。あなたの 'list2'は空です:' list2 = "" '。あなたは 'list1.index(word)'を意味していないと確信していますか? –

答えて

0

[OK]を - そうではなく、あなたのコードを修正するよりも、私は再する自由を取りました-書いてください。 うまくいけば、私は論理が正しいと思う。

また、ファイルを変数として、python内の組み込み変数として使用しないでください。それは問題を生み出し、良い習慣でもない。ここで

は、高レベルの擬似コードは、このリストを読んで、入力文からユニークワードのリストに追加UserSentence

  • として文字列のリストに

  • 変換

    • 読むユーザー入力です as PositionOfWords

    • 今すぐユーザー入力用の文字列のリストを参照し、文字列を作成してください newSentence

      UserSentence = input("enter sentence:").lower().split() 
      #list to store unique words 
      PositionOfWords = [] 
      
      newSentence = '' #new sentence 
      
      
      #Read each word in UserSentence and process 
      for word in UserSentence: 
          if word not in PositionOfWords: 
           PositionOfWords.append(word) 
      
      #Once we have unique words list, Lets get their positions in given sentence 
      for word in UserSentence: 
          #get position of word append to new sentence 
          newSentence += str(PositionOfWords.index(word)) 
      
      newSentence = ' '.join(newSentence) 
      
      myfile = open ("filename.txt","w") 
      myfile.writelines('UserSentence = {} '.format(UserSentence)) 
      myfile.writelines('\n') 
      myfile.writelines('PositionOfWords = {} '.format(PositionOfWords)) 
      myfile.writelines('\n') 
      myfile.writelines('newSentence = {} '.format(newSentence)) 
      myfile.close() 
      
      print PositionOfWords 
      print newSentence 
      

      ファイル出力:

      PositionOfWords
    • からそのインデックス位置はここ

    を提出する

  • 書き込みnewSentenceを提出する
  • 書き込みPositionOfWordsをファイルへの書き込みUserSentenceがコードを働いていると

    UserSentence = ['this', 'is', 'repeating', 'sentence', 'this', 'is', 'repeating', 'sentence']
    PositionOfWords = ['this', 'is', 'repeating', 'sentence']
    newSentence = 0 1 2 3 0 1 2 3