期望的str实例,int发现。如何将int更改为str以使此代码有效?

时间:2017-02-16 13:16:20

标签: string python-3.x integer

我正在尝试编写分析包含多个单词且没有标点符号的句子的代码。我需要它来识别输入的句子中的单个单词并将它们存储在列表中。我的例句是“不要问你的国家可以为你做什么,问你能为国家做些什么。然后我需要将单词的原始位置写入文本文件。这是我目前的代码,其中的部分取自我发现的其他问题,但我无法让它工作

myFile = open("cat2numbers.txt", "wt")   
list = []  # An empty list 
sentence = ""  # Sentence is equal to the sentence that will be entered

print("Writing to the file: ", myFile) # Telling the user what file they will be writing to 
sentence = input("Please enter a sentence without punctuation ") # Asking the user to enter a sentenc
sentence = sentence.lower() # Turns everything entered into lower case
words = sentence.split() # Splitting the sentence into single words
positions = [words.index(word) + 1 for word in words]
for i in range(1,9):
    s = repr(i)
    print("The positions are being written to the file")
    d = ', '.join(positions) 
    myFile.write(positions) # write the places to myFile
    myFile.write("\n")
    myFile.close() # closes myFile
    print("The positions are now in the file") 

我得到的错误是TypeError:序列项0:预期str实例,找到int。有人可以帮助我,非常感谢

2 个答案:

答案 0 :(得分:1)

由于您在字符串上加入.join,因此错误源于ints

所以简单的解决方法就是使用:

d = ", ".join(map(str, positions))

str列表的所有元素上映射positions函数,并在加入之前将它们转换为字符串。

但是,这并不能解决你所有的问题。您出于某种原因使用了for循环,在写入后.close文件。{1}}在随后的迭代中,您尝试写入已关闭的文件时会收到错误。

除此之外,list = []是不必要的,应避免使用名称list; sentence的初始化也是不必要的,您不需要像这样初始化。另外,如果您想要8个句子(for循环),请在完成工作之前先进行循环。

总而言之,尝试这样的事情:

with open("cat2numbers.txt", "wt") as f:   
    print("Writing to the file: ", myFile) # Telling the user what file they will be writing to 
    for i in range(9):
        sentence = input("Please enter a sentence without punctuation ").lower() # Asking the user to enter a sentenc
        words = sentence.split() # Splitting the sentence into single words
        positions = [words.index(word) + 1 for word in words]
        f.write(", ".join(map(str, positions))) # write the places to myFile
        myFile.write("\n")
        print("The positions are now in the file")

这使用with语句来处理在幕后为你关闭文件。

答案 1 :(得分:0)

正如我所看到的,在for循环中,你尝试写入文件,而不是关闭它,而不是再次写入CLOSED FILE。这不是问题所在吗?