将字符串元素转换为类属性(py 2.7) [英] Convert string elements to class attributes (py 2.7)
本文介绍了将字符串元素转换为类属性(py 2.7)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,我想使用元素将它们转换为类的attrs。
i have a string, and i want to use the elements to convert them into attrs of a class.
@staticmethod
def impWords():
#re
tempFile = open('import.txt','r+')
tempFile1 = re.findall(r'\w+', tempFile.read())
for i in range(len(tempFile1)):
new=word(word.id=i,word.data=str(tempFile1[i]), word.points=int(tempFile1[i]+1))
Repo.words.append(word)
print str(Repo.words)
下面的错误弹出,我怎么可以修复这我试过一些想法,但已经没有成功。
the following error pops up, how can i repair this i tried some ideas i had but it didnt worked out.
File "D:\info\F P\Lab\lab5.7\Scramble\Repository\Rep.py", line 82, in impWords
new=word(id=int(i),data=str(tempFile1[i]), points=int(tempFile1[i]+1))
TypeError: cannot concatenate 'str' and 'int' objects
推荐答案
:
int(tempFile1[i]+1)
您的 tmpFile [i]
是一个字符串。您不能将整数 1
添加到字符串。您可以尝试将字符串转换为整数,然后添加:
Your tmpFile[i]
is a string. You cannot add the integer 1
to a string. You can try to convert your string into an integer and add the one afterwards:
int(tempFile1[i])+1
所以整行看起来像这样:
So the whole line looks like this:
new=word(word.id=i,word.data=str(tempFile1[i]), word.points=int(tempFile1[i])+1)
更新:无论如何,这可能不会工作。考虑这个选择(你必须正确定义单词类):
UPDATE: Anyway, this is probably not going to work. Consider this alternative (you have to define the word-class properly):
@staticmethod
def impWords():
with open('import.txt','r+') as f:
for i, word in enumerate(re.findall(r'\w+', f.read())):
Repo.words.append(word(id=i, data=word, points = int(word)+1))
这篇关于将字符串元素转换为类属性(py 2.7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文