【问题标题】:Convert string elements to class attributes (py 2.7)将字符串元素转换为类属性(py 2.7)
【发布时间】:2012-02-04 15:18:53
【问题描述】:

我有一个字符串,我想使用这些元素将它们转换为一个类的属性。

@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

【问题讨论】:

  • (tempFile1[i]+1)) 不能连接 'str' 和 'int' 对象。你想做什么?
  • word(word.id=i,word.data=str(tempFile1[i]), word.points=int(tempFile1[i]+1)) 这是什么奇怪的结构
  • 进程:1 导入文件 2 拆分它 3 从新的 lsit 创建 'word' 类的对象 (tempFile1[i]+1))

标签: python oop class


【解决方案1】:

问题出在这里:

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)

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

@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(): def __init__(self,ID,data,points): self.ID = ID self.data = data self.points=points ID = int data = str points = int def prt(self): print 'ID: ' + str(self.ID) + ' word: ' +str(self.data)+' pts value: '+str(self.points) 错了吗?或者为什么应该精确修复
  • @BogdanMaier - 无法在评论中读取您的定义(缺少换行符),但您定义它的方式可能没问题。只需注意大小写(ID/id)。
【解决方案2】:

如果你想解决你的问题?只需制作 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]

【讨论】:

  • 谢谢我m beginner in programming and i work on a scramble game atm, i hope with tiem ill 改善我的差距。我学习编程大约 4 个月 :)
  • 据我了解,您在使用 (tempFile1[i]+1)) 转到下一个位置的主题开始时的评论?如果这是对的,那么你就是不对的。我在下面的答案中发布我的解释
【解决方案3】:

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

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 算法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多