尝试压缩文本时的ValueError

时间:2017-03-02 19:12:00

标签: python

我被赋予了一项任务,即开发一个识别句子中单个单词的程序,将这些单词存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。我已经完成了代码但是当我运行它时,我收到一个错误:

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

1 个答案:

答案 0 :(得分:0)

好的 - 所以我没有修复你的代码,而是冒昧地重写它。 希望我的逻辑是正确的。

另外,请不要将 file 用作变量,作为python中的内置变量。它会产生问题,也不是一种好的做法。

这是高级伪代码

  • 阅读用户输入

  • 转换为字符串列表为UserSentence

  • 阅读此列表并附加到输入句子中的唯一单词列表 作为PositionOfWords
  • 现在浏览用户输入的字符串列表并构造一个字符串 newSentence及其位置来自PositionOfWords
  • 将UserSentence写入文件
  • 将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 

文件输出:

  

UserSentence = ['this','is','重复','句子','this','是','重复','句子']   PositionOfWords = ['this','is','重复','句子']   newSentence = 0 1 2 3 0 1 2 3