Python 尝试压缩文本时出现ValueError
我的任务是开发一个程序,识别句子中的单个单词,将它们存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。我已经完成了代码,但当我运行它时,我得到一个错误:Python 尝试压缩文本时出现ValueError,python,Python,我的任务是开发一个程序,识别句子中的单个单词,将它们存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。我已经完成了代码,但当我运行它时,我得到一个错误: 回溯(最近一次呼叫最后一次): 文件第11行,在 PositionOfWord=list2.索引(word) ValueError:未找到子字符串 这是我的密码: UserSentence = input("enter sentence:").lower() words = UserSentence.split() Pos
回溯(最近一次呼叫最后一次):
文件第11行,在
PositionOfWord=list2.索引(word)
ValueError:未找到子字符串
这是我的密码:
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
好的-所以我没有修改你的代码,而是冒昧地重新编写了它。 希望我的逻辑正确 另外,请不要将文件用作变量,作为python中的内置变量。这会产生问题,也不是一个好的做法 下面是高级伪代码
- 读取用户输入
- 将字符串列表转换为用户语句
- 阅读此列表并将其附加到输入句子中的唯一单词列表中 作为词的位置
- 现在浏览用户输入的字符串列表并构造一个字符串 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
文件输出:
UserSession=[“这”、“是”、“重复”、“句子”、“这”、“是”、“重复”、“句子”]PositionOfWord=[“这”、“是”、“重复”、“句子”]
新闻事件=0 1 2 3 0 1 2 3
错误是显而易见的
list2
为空,因此无法获取任何单词的索引。你真的是自己写的吗?是的,我做的事情是我不是一个好的程序员,无论如何谢谢。index
检索列表中元素的索引(或字符串,但你试图使用它,好像目标是一个列表),而你的list2
是空的:list2=”“
。你确定你的意思不是list1.index(word)
?