【问题标题】:Appending elements to an array instance variable and print out - Python将元素附加到数组实例变量并打印出来 - Python
【发布时间】:2014-03-05 05:27:32
【问题描述】:

我正在尝试读取文件并提取记录并在类中打印文件。我得到的错误是该对象没有附加功能?我已将它声明为一个数组,但它似乎无法识别它。任何提示问题是什么?这是解决问题的有效方法吗?

import os 

class URL():
    Test=[]
    def read(self,file):
        for l in open(file):
            fields=l.split(',')
            company=fields[1].replace(" ",'+')
            adress="+".join((str(fields[5]),str(fields[11]) ) )
            self.Test.append( "".join(("http://www.someurl/market-search?q=",company)))
    def Print(self):
        for i in Test:
            return i 

ROOT = os.getcwd()
START_URL=URL()
START_URL.read(ROOT+'\Company_Lists\Test_of_company.csv')

print START_URL.Print

【问题讨论】:

  • 你能给出你得到的确切错误吗?
  • self.Test != 测试。你还没有定义 self.Test
  • self.Test.append("".join(("someurl/marker-search?=company))) AttributeError 'function' object has no attribute 'append'
  • @M4rtini,你是对的,但这里因为Print() 不写信给Test,它会从URL 继承Test。它会起作用,但它绝对是糟糕的形式
  • @wnnmaw 错误很可能是在读取功能中,他尝试在打印功能中使用self.Test而不是。

标签: python arrays append instance-variables


【解决方案1】:

我会重写这个:

import os 
import os.path


class URL(object):
    Test = []
    def read(self, filename):
        with open(filename) as f:
            for line in f:
                fields = line.split(',')
                company = fields[1].replace(" ", '+')
                self.Test.append("http://www.someurl/market-search?q={0}".format(company))

    def print(self):
        for i in self.Test:
            print i 


def main():
    root = os.getcwd()
    start_url = URL()
    p = os.path.join(root, 'Company_Lists', 'Test_of_company.csv')
    start_url.read(p)
    start_url.print()


if __name__ == '__main__':
    main()

【讨论】:

  • 这个脚本有两个小改动,打印需要打印,否则它会尝试调用打印函数。我需要从 os.join.path 中删除 [],因为 open() 不能将列表作为参数。我一直对 stackoverflow 社区感到惊讶!万分感谢。你的字符串操作比我的好很多:)。
  • 哇,不能使用print 作为方法名吗?令人惊讶。
  • 感谢您的建设性意见,您是最棒的 Hughdbrown。
猜你喜欢
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 2012-12-13
  • 1970-01-01
  • 2021-07-10
  • 2021-07-04
  • 1970-01-01
  • 2020-04-03
相关资源
最近更新 更多