将字符串元素转换为类属性(py 2.7)

2024-10-01 09:15:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,我想使用元素将它们转换成类的属性。你知道吗

@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)

下面的错误弹出,我如何修复这个我尝试了一些想法,但没有成功。你知道吗

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

Tags: 字符串inreidnewdatarepotempfile
3条回答

如果你不想解决你的问题?只需使int(tempFile1[i])+1,但这段代码绝对不是python的方式。你知道吗

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]

问题在于:

int(tempFile1[i]+1)

你的tmpFile[i]是一个字符串。不能将整数1添加到字符串中。您可以尝试将字符串转换为整数,然后再添加一个:

int(tempFile1[i])+1

所以整条线看起来是这样的:

new=word(word.id=i,word.data=str(tempFile1[i]), word.points=int(tempFile1[i])+1)

更新:无论如何,这可能行不通。考虑这个替代方案(您必须正确定义单词class):

@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))

所以如果你明白这是你想要的

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()))]

但如果你想得到文件中每个单词的计数,请查看mapreduce算法

相关问题 更多 >