Convert string elements to class attributes (py 2.

2019-08-22 09:49发布

问题:

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

回答1:

The problem is here:

int(tempFile1[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))


回答2:

If you whant to solve your problem? Just make int(tempFile1[i]) + 1, but this code is absolutely not python way.

f = file('your_file')
ids_words = enumerate(re.findall(r'\w', f.read()))
out_mas = [word(word.id = id, word.data = data, word.points = int(data) + 1) for id, data in ids_words]


回答3:

So if understand this is what you want

class Word(object):
    def __init__(self, id, data):
        self.id = id
        self.data = data

f = file('your_file')
result = [Word(id, data) for id, data in enumerate(re.findall(r'\w+', f.read()))]

But if you want get a count of each word in file look at mapreduce algorithm



标签: python oop class