简体   繁体   English

TypeError:-:“ str”和“ int”的不受支持的操作数类型

[英]TypeError: unsupported operand type(s) for -: 'str' and 'int'

Right now my code will create a text file including the positions of each word in a sentence in a list, and each word in a list - like so: 现在,我的代码将创建一个文本文件,其中包括列表中句子中每个单词的位置以及列表中每个单词的位置,如下所示:

文件内容

My code then opens back up the file and should be able to recreate the sentence using those positions and the words in the text file, but it doesn't seem to work with with the readlines code for some reason. 然后,我的代码将打开该文件的备份,并且应该能够使用这些位置和文本文件中的单词来重新创建句子,但是由于某种原因,它似乎无法与readlines代码一起使用。

openfilename = open(openfilename,"r")
readlines = openfilename.readlines()

wordslist = readlines[0]
positionslist = readlines[1]

print(positionslist)
print(wordslist)

originalsentence = " ".join([wordslist[x-1] for x in positionslist])
print(originalsentence)

For example this comes up with wordslist and positionslist coming out as: 例如,这带有wordslist和positionslist,结果为:

[1, 2, 3, 2]
['test123', ',', '.']

Where as if I were to use: 好像我要使用的那样:

positionslist = [1, 2, 3, 2]
wordslist = ['test123', ',', '.']
originalsentence = " ".join([wordslist[x-1] for x in positionslist])
print(originalsentence)

It would work, and I have no idea why because, as a newcomer to python, you'd think they'd work the same. 它将起作用,而且我不知道为什么,因为,作为python的新手,您会认为它们会发挥相同的作用。 Looking at other people's post with the same error I'm supposedly missing a 看着别人的帖子有同样的错误我应该错过了

(int(...)

line of code somewhere but I'm not sure where, or if that's even the problem. 某处的代码行,但是我不确定在哪里,或者甚至是问题所在。

EDIT: this answer assumes a "raw" format. 编辑:此答案假定为“原始”格式。 It won't work here. 它在这里行不通。 It would work if readlines[1] was already a list of strings obtained by splitting a line like "1 4 5 6 7" , which isn't the case here since line contains a python list written as a str(list) . 如果readlines[1]已经是通过分割像"1 4 5 6 7"这样的行而获得的字符串列表,那将是可行的,这里不是这种情况,因为line包含写为str(list)的python列表。 ast.literal.eval is the right choice in that case, if the input format is satisfying and not a mistake in the first place. 在这种情况下, 如果输入格式令人满意并且首先没有出现错误, ast.literal.eval是正确的选择。

when you do: 当您这样做时:

positionslist = readlines[1]

there's no way you get something other than a list of strings containing integers. 除了包含整数的字符串列表之外,您别无选择。 You have to convert them for example like this: 您必须像这样转换它们:

positionslist = [int(x) for x in readlines[1]]

In your hardcoded example, you're using integers directly and it works. 在您的硬编码示例中,您直接使用了整数并且它可以工作。

Note: as cricket_007 suggested, since you just iterate on positionslist , you can use 注意:正如cricket_007所建议的那样,由于您只需要迭代positionslist ,因此可以使用

positionslist = map(int,readlines[1])

It applies the int function to each item of readlines[1] , returns an iterable (returns list in Python 2, so not that much different from the list comprehension above in that case). 它将int函数应用于readlines[1]每一项,返回一个可迭代(在Python 2中返回list ,因此与上面的列表理解没有太大区别)。

In Python 3, that avoids to create/allocate a list that you don't need since you don't use indexes (if you want to debug it you can't since you can iterate only once on it), so it is more performant. 在Python 3中,这避免了创建/分配不需要的列表,因为您不使用索引(如果要调试它,则无法进行,因为您只能对其进行一次迭代),所以它更多表演者。

of course, if some line is not a digit it will crash with an explicit error ValueError: invalid literal for int() with base 10 当然,如果某行不是数字,则将崩溃,并显示显式错误ValueError: invalid literal for int() with base 10

Another solution is to use ast.literal_eval() to convert your string u'[1, 2, 3, 2] directly into a list of interger: 另一个解决方案是使用ast.literal_eval()将字符串u'[1, 2, 3, 2] ast.literal_eval() u'[1, 2, 3, 2]直接转换为整数列表:

import ast

with open(openfilename, "r") as f:
    positionslist = ast.literal_eval(f.readline())
    wordslist = ast.literal_eval(f.readline())

    print(" ".join([wordslist[x-1] for x in positionslist]))

Also, the with statement replace a try and catch. 同样,用with语句替换try and catch。 It also automatically close the file after the block. 阻止之后,它也会自动关闭文件。

The issue is, when you read from the file, the values are of str type by default. 问题是,当您从文件中读取时,默认情况下值是str类型的。 And when you try to do x-1 in [wordslist[x-1] for x in positionslist] , you get error because you try to subtract 1 from string. 当您尝试在[wordslist[x-1] for x in positionslist]x-1时,会出错,因为您尝试从字符串中subtract 1。 In order to fix this, convert positionslist to list of int's as: 为了解决此问题,请将positionslist转换为int的列表,如下所示:

positionslist = readlines[1]
positionslist = map(int, positionslist) # <-- add this line in your code 

and your code will work. 这样您的代码就会起作用。 Check map() to know about it. 检查map()以了解它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM